我正在嘗試從C創建一個python進程,并從python腳本獲取打印結果。在
這就是我的C代碼:namespace ConsoleApp1
{
public class CreateProcess
{
public String PythonPath { get; set; }
public String FilePath { get; set; }
public String Arguments { get; set; }
public Process process;
public void run_cmd()
{
this.process = new Process();
ProcessStartInfo start = new ProcessStartInfo
{
FileName = this.PythonPath,
Arguments = string.Format("{0} {1}", this.FilePath, this.Arguments),
UseShellExecute = false,
RedirectStandardOutput = true,
};
this.process.StartInfo = start;
this.process.OutputDataReceived += p_OutputDataReceived;
this.process.Start();
this.process.BeginOutputReadLine();
//this.process.WaitForExit();
}
void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.Write(e.Data);
}
}
class Program
{
static void Main(string[] args)
{
CreateProcess test = new CreateProcess();
test.PythonPath = "mypathtopython.exe";
test.FilePath = "pythonfilename";
test.Arguments = "arg1 arg2 arg3";
test.run_cmd();
}
}
}
當我刪除WaitForExit()方法時,會出現以下錯誤:
^{2}$
當我保留它時,它可以工作,但是當python進程停止運行時(這是意料之中的),輸出將打印到我的控制臺。我希望它能實時發生…知道我哪里做錯了嗎?在
這在python中可能是個問題,而不是在C中,但我不確定如何修復它。這是我的python測試腳本:import time
import os
import sys
print("First example")
time.sleep(10)
print("Arguments given:",sys.argv)
我也試過用系統stdout.flush()但是沒有成功。在