在真实的tim中用C捕获控制台python打印

2024-05-01 22:00:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从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()但是没有成功。在


Tags: testimportnewgetstringpublicthisprocess