c# - c#运行python脚本并读取输出导致
问题描述
我想运行 python 脚本,但我的问题是我在最后一次获得所有输出,而不是逐行(我的脚本打印时间 10 次,每次后休眠 1 秒)。
这是我的代码:
static void Main(string[] args)
{
string cmd = @"C:\test.py";
string pythonPath = @"C:\python.exe";
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = pythonPath;//cmd is full path to python.exe
start.Arguments = cmd;//args is path to .py file and any cmd line args
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
while (!process.StandardOutput.EndOfStream)
{
string result = process.StandardOutput.ReadLine();
Console.Write(result);
}
}
}
}
更新
string cmd = @"C:\test.py";
string pythonPath = @"C:\Python37\python.exe";
Process process = new Process();
process.StartInfo.FileName = "python";
process.StartInfo.Arguments = cmd;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
private static void OutputHandler(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
Python 脚本
import time
from datetime import datetime
count = 0
while count < 3:
print(datetime.now())
time.sleep(1)
count += 1
print('DONE')
解决方案
推荐阅读
- mysql - nodejs mysql插入空日期时间字段
- c++ - 代码逻辑有什么问题?
- vue.js - 如何在 router.back() 上为 VueJS 中的深层链接项目设置默认值
- python - 如何在 Azure DevOps(服务器)管道中测试 dockerized 应用程序?
- spring - Spring mvc表单提交绑定结果抛出错误
- sql - 监视表的活动(特定行上的选择数)
- java - 使用 OpenOffice java api 保存文档会引发异常
- python - 如何对列表列表中的向量数组求和?
- amazon-s3 - Terraform`aws_iam_policy_document`数据块中多个条件的正确语法是什么
- jboss - 创建数据源时无法识别区域设置错误(与 oracle db 连接)