【问题标题】:WPF C# - get python version by cmdWPF C# - 通过 cmd 获取 python 版本
【发布时间】:2018-04-16 13:22:39
【问题描述】:

我尝试使用 python 版本,所以我使用 cmd 和命令“python --version”启动了一个进程。

我先试试这个:

     using (System.Diagnostics.Process p = new System.Diagnostics.Process())
              {
               p.StartInfo.UseShellExecute = true;
               p.StartInfo.RedirectStandardOutput = false;
               p.StartInfo.FileName = "cmd.exe";
               p.StartInfo.Arguments = "/k C:/Python36/python --version";
               p.StartInfo.CreateNoWindow = false;
               var retorno = p.Start();
              }

然后打开一个 cmd 窗口并返回:

cmd return

而不是这个,我需要这个结果返回到我的 WPF 应用程序,所以我试试这个:

public static string GetPythonVersion()
    {
      string command = "python --version";
      string output = null;
      using (System.Diagnostics.Process p = new System.Diagnostics.Process())
      {
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = String.Format(@"/c {0}\{1} ", "C:/Python36/", command);
        p.StartInfo.CreateNoWindow = true;
        if (p.Start())
          output = p.StandardOutput.ReadToEnd();
      }
     return output;
   }

返回空字符串给我。 但是举个例子,如果我使用相同的代码将“pip list”返回给我的 wpf 应用程序运行良好,但在这种情况下,字符串返回空......

【问题讨论】:

  • 你需要等待它结束才能读取输出。否则它可能还没有打印出来
  • 我知道,有一个函数 p.WaitForExit(int miliseconds);但在这种情况下并不能解决问题
  • 好吧,我试过了,新的 WPF 应用程序,MainWindow 中有一个 TextBox,设置文本框的 Text 属性的方法完全相同(我什至在同一位置安装了 Python 3.6.5),并且它作品。您的问题出在其他地方,但很难说是在哪里。
  • 对于 Windows cmd.exe,路径分隔符是 \ ,但不是 /...
  • 我再次尝试使用与您相同的 Python 版本.. 3.6.5 并返回相同的空字符串。我在 Python 官方网站上阅读了关于 link 的“python --version”命令并说:“打印 Python 版本号并退出”所以,当我发送命令执行并将输出到python提示然后退出到pyton提示..然后我的版本输出在普通的Windows命令提示符下不再存在?

标签: c# python wpf command-line cmd


【解决方案1】:

好的,伙计们。我发现代码有什么问题。下面是正确的代码:

public static string GetPythonVersion()
    {
      string command = "python --version";
      string output = null;
      using (System.Diagnostics.Process p = new System.Diagnostics.Process())
      {
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = false;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = String.Format(@"/c {0}\{1} ", "C:/Python36/", command);
        p.StartInfo.CreateNoWindow = true;
        if (p.Start())
          output = p.StandardError.ReadToEnd();
      }
     return output;
   }

是的,python 版本在 StandardError 上,因为正如您所见:

https://docs.python.org/3/using/cmdline.html#generic-options

"打印 Python 版本号并退出。"

所以当在 cmd 上运行命令时,在 StandardOutput 上没有任何内容... 感谢大家试图帮助我!现在这个案子已经结束了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-24
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 2014-08-16
    • 2015-03-21
    • 1970-01-01
    相关资源
    最近更新 更多