首页 > 解决方案 > 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')

标签: c#process

解决方案


推荐阅读