c# - 从 C# 调用 python 脚本不起作用,不会引发错误

标签 c# python

我正在编写一个 C# 程序来执行带有一些参数的 python 脚本。即使没有错误并且 Process ExitCode 为 0(通过调试器检查),程序也不会执行(它应该不仅打印出消息,而且还写入文件)。我哪里出错了?

    static private string ExecutePython(string sentence) {
        // full path of python interpreter  
        string python = @"C:\Python27\python.exe";

        // python app to call  
        string myPythonApp = @"C:\Users\user_name\Documents\pos_edit.py";

        // Create new process start info 
        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

        // make sure we can read the output from stdout 
        myProcessStartInfo.UseShellExecute = false;
        myProcessStartInfo.RedirectStandardOutput = true;


        myProcessStartInfo.Arguments = string.Format("{0} {1}", myPythonApp, sentence);

        Process myProcess = new Process();
        // assign start information to the process 
        myProcess.StartInfo = myProcessStartInfo;

        // start process 
        myProcess.Start();

        // Read the standard output of the app we called.  
        StreamReader myStreamReader = myProcess.StandardOutput;
        string myString = myStreamReader.ReadToEnd();

        // wait exit signal from the app we called 
        myProcess.WaitForExit();

        // close the process 
        myProcess.Close();

        return myString;
}

最佳答案

您将 myProcess.WaitForExit(); 放在了错误的位置; 等待直到Python执行脚本:

...
myProcess.Start();

StreamReader myStreamReader = myProcess.StandardOutput;

// first, wait to complete
myProcess.WaitForExit();

// only then read the results (stdout)
string myString = myStreamReader.ReadToEnd();
...

关于c# - 从 C# 调用 python 脚本不起作用,不会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031777/

相关文章:

c# - 将托管 C# 列表返回到非托管 C++ 代码

c# - 合并键匹配的键值对列表

c# - 如何在c sharp中循环json对象内部的json对象

python - 在另一个方法中运行一个方法。 Python

c# - NHibernate to Linq 获取没有出过书的作者

c# - Marshal.SizeOf 计算大小错误

python - PyCharm 记录输出颜色

Python 报告框架

python - 您将如何实现除数函数?

python - 在 python 中处理列表