【发布时间】:2021-10-23 18:32:35
【问题描述】:
我想通过cmd实时执行python脚本的结果。
我的带有启动 pyhton 脚本的 C# 代码:
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
// Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
// Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
private void backgroundWorker_sizzer_DoWork(object sender, DoWorkEventArgs e)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("cd C:\\Users\\");
cmdProcess.StandardInput.WriteLine("py test.py"); //Execute script
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
test.py 文件包含简单示例:
import time
time.sleep(5) # Sleep for 5 seconds
print("hello")
time.sleep(10) # Sleep for 10 seconds
print("hello")
time.sleep(15) # Sleep for 15 seconds
print("hello")
time.sleep(1) # Sleep for 1 seconds
现在,当我运行 backgroundworker 时,它会立即显示所有 hello - 当 python 脚本结束他的执行时。
我想要的只是一个一个实时显示你好。当我通过 cmd 手动启动它时,它运行良好并实时显示“你好”。
【问题讨论】:
-
“我希望通过 cmd 实时执行 python 脚本的结果。” - 定义“实时”。
-
什么是执行?
-
实时意味着执行打印时立即在控制台日志中显示结果