【问题标题】:C# When I open the console, there is no command entered and it immediately disappearsC#当我打开控制台时,没有输入任何命令,它立即消失
【发布时间】:2020-01-30 18:29:44
【问题描述】:
private void RunApp_Click(object sender, RoutedEventArgs e)
    {
        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Python\PythonCore\3.7\InstallPath");
        if (key != null)
        {
            object path = key.GetValue("ExecutablePath");
            string comm = "/C " + System.IO.Path.GetDirectoryName(path as string) + @"\python " + 
                System.IO.Path.GetDirectoryName((string)SelectProjectFolder.Content) + "main.py";
            System.Diagnostics.Process.Start("cmd.exe", comm);
        }
    }

错在哪里?控制台在没有命令的情况下打开并立即关闭。用etip做什么。我需要通过控制台运行一个 .py 文件。我通过 Key 获取 Python 的路径并将路径添加到 Py 文件。但是当您在控制台中打开命令时,不会。 (谷歌翻译)

【问题讨论】:

  • 在调用 process.start 之前使用调试器检查 comm 变量的内容
  • 预期行为,例如当您双击 yhe py 文件时

标签: c# python-3.x wpf cmd


【解决方案1】:

您将"/C" 传递到命令窗口,这意味着“执行字符串指定的命令,然后终止”(在命令行输入cmd.exe /? 以查看所有参数它接受,以及每个的描述)。

如果您希望窗口保留,请尝试传递"/K"

string comm = "/K " + …

然后您应该能够看到报告的错误(如果有的话)。


您很可能在 SelectProjectFolder.Content"main.py" 之间缺少反斜杠字符 ('\')。为了解决这个问题,通常倾向于使用Path.Combine 创建目录路径:

Path.Combine(Path.GetDirectoryName((string)SelectProjectFolder.Content)), "main.py")

如果问题是找不到 python.exe 的路径,您可能想要做的另一件事是尝试各种注册表项。我认为这些是正确的,但它们应该得到验证:

private string GetPythonExePath(string ver = "3.7")
{
    return (Registry.LocalMachine
        .OpenSubKey($@"SOFTWARE\Python\PythonCore\{ver}\InstallPath")?
        .GetValue("ExecutablePath") ??
            Registry.CurrentUser
                .OpenSubKey($@"Software\Python\PythonCore\{ver}\InstallPath")?
                .GetValue("ExecutablePath") ??
            Registry.LocalMachine
                .OpenSubKey($@"SOFTWARE\Wow6432Node\Python\PythonCore\{ver}\InstallPath")?
                .GetValue("ExecutablePath"))?
        .ToString();
}

此外,您可以将 python 文件的路径与Process.Start 命令分开设置,以使调试更容易一些(您可以在Process.Start 行上设置断点并在启动进程之前检查参数):

var pythonExePath = GetPythonExePath();            

if (pythonExePath!=null)
{
    var pythonFile = Path.Combine(SelectProjectFolder.Content.ToString(), "main.py");
    Process.Start("cmd.exe", $"/K {pythonExePath} {pythonFile}");
}

【讨论】:

    【解决方案2】:

    您可以使用 ProcessStartInfo:

    string path = @"C:\Program Files\Python";
    string args = "main.py";
    ProcessStartInfo pinfo = new ProcessStartInfo(path);
    pinfo.Arguments = args;
    using(Process proc = Process.Start(pinfo))
    {
        proc.WaitForExit();
        if(proc.ExitCode == 0)
        {
            // Normal exit
        }
        else
        {
            // Exit with error
        }
    }
    

    如果您的代码中有对 System.Diagnostics 的引用,则可以使用 ProcessStartInfo。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 1970-01-01
      • 2011-10-27
      • 2014-06-23
      • 1970-01-01
      • 2014-09-07
      • 2014-11-24
      • 2016-08-30
      相关资源
      最近更新 更多