主流语言运行系统命令

文章展示了C#和Python中如何执行命令行操作并获取返回值。C#部分使用`Process`类来运行命令,读取输出并处理错误代码。Python部分则利用`subprocess.Popen`进行命令执行并检查返回状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C# 版本 带返回值的:

int i = 0;
do {
    Console.WriteLine(i++);
    Console.WriteLine();
    Cmd.RunCmd("ipconfig");
    Thread.Sleep(5000);
} while (1 == 1);
class Cmd
{
    private static string CmdPath = @"cmd.exe";
    /// <summary>
    /// 执行cmd命令 返回cmd窗口显示的信息
    /// 多命令请使用批处理命令连接符:
    /// <![CDATA[
    /// &:同时执行两个命令
    /// |:将上一个命令的输出,作为下一个命令的输入
    /// &&:当&&前的命令成功时,才执行&&后的命令
    /// ||:当||前的命令失败时,才执行||后的命令]]>
    /// </summary>
    ///<param name="cmd">执行的命令</param>
    public static string RunCmd(string cmd)
    {
       cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
       // cmd = cmd.Trim();
        using (Process p = new Process())
        {
            p.StartInfo.FileName = CmdPath;
            
            p.StartInfo.Arguments = "/c " + cmd; 
            p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
            p.StartInfo.CreateNoWindow = false; //不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口写入命令
            // p.StandardInput.WriteLine(cmd);
            // p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();//等待程序执行完退出进程
            Console.WriteLine("Err code:" + p?.ExitCode);
            p.Close();
            //将cmd的输出展示在控制台
            Console.WriteLine(output);

            return output;
        }
    }

    public static bool RunCmdPs(string cmdStr)
        {
            bool result = false;
            try
            {
                using (Process myPro = new Process())
                {
                    //指定启动进程是调用的应用程序和命令行参数
                    ProcessStartInfo psi = new ProcessStartInfo(CmdPath, cmdStr);
                    psi.UseShellExecute   = true;
                    psi.CreateNoWindow = true;

   //zprocessStartInfo.RedirectStandardOutput = false;
                    // myPro.StartInfo = psi;
                    Process? process = Process.Start(psi);
                    myPro.WaitForExit();
                    Console.WriteLine("Err code:" + process?.ExitCode);
                    result = true;
                }
            }
            catch
            {

            }
            return result;
        }
}

运行结果:

在这里插入图片描述

Python版本的 带返回值的:

def run_cmd_Popen_fileno(cmd_string):
    """
    执行cmd命令,并得到执行后的返回值,python调试界面输出返回值
    :param cmd_string: cmd命令,如:'adb devices'
    :return:
    """
    import subprocess
    
    print('运行cmd指令:{}'.format(cmd_string))
    return subprocess.Popen(cmd_string, shell=True, stdout=None, stderr=None).wait()

# 注意调用顺序 先定义函数
result = run_cmd_Popen_fileno("docker-compose build")
i = 0
while result !=0:
    print("第" + str(i) + "次构建")
    print("---------------------------------------------------")
    result = run_cmd_Popen_fileno("docker-compose build")
    i = i + 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

helloworddm

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值