运行Python脚本的进程对象无法成功重定向输出

2024-09-28 01:28:55 发布

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

我正在通过Process类在c程序中运行一个简单的python脚本。下面是我实际运行脚本时使用的代码:

    public PythonScript (string filePathDir, string args, Action<string> write)
    {
        this.filePathDir = filePathDir;
        this.args = args;
        this.write = write;

        script_thread = new Thread (Run);
        script_thread.Start ();
    }

    private void Run()
    {
        process = new ProcessStartInfo ();
        process.Arguments = args;
        process.FileName = filePathDir;
        process.UseShellExecute = false;
        process.RedirectStandardOutput = true;

        p = Process.Start (process); // p is declared as "Process p;"
        while (true) {
            write ("running");
            string foo = p.StandardOutput.ReadLine ();
            write ("running1");
            write (foo);
        }
    }

我实际创建PythonScript对象的方法是:

PythonScript py = new PythonScript("python3", "HeartAPI.py", Write)

其中Write是我的输出方法(用于打印信息)。它的格式来自here。(注:我叫python3而不是python.exe或者其他原因,因为我在KUbuntu环境下运行)

我遇到的问题是,当我运行我的脚本(它是一个基本的api)时,api是可访问和可用的,但是每次python脚本有一个print()调用时,没有任何东西通过我的Write函数输出。但是,我知道这不是我传递方法的方式,因为调用write("running");起作用,并且会显示它。在

有人知道为什么我的python输出流没有通过我的write方法吗?我在网上找不到任何其他与此问题有关的例子,所以任何帮助将不胜感激!在

编辑:澄清。我的python脚本确实运行,并且成功地完成了它的操作。然而,据我所知,上述脚本的输出没有得到适当的重定向。传递到PythonScript对象的Write(string)方法工作正常,因为命令write("running");执行得很好,并且显示得很好。为什么Python脚本的输出没有被重定向到我的write()方法中?在

编辑2:为了响应我尝试的答案,我在PythonScript构造函数的其余代码下添加了一个script_thread.Join()调用。以下是更新后的代码:

^{pr2}$

我还向控制台添加了一个对output的调用,它指示线程何时加入,而线程永远不会得到输出。尝试此代码时,我的GUI窗口从未出现。但是,我有一个日志记录系统,它被写入了,这是应该转到我的GUI控制台的输出:

 running
11:11:44-  Closing down Heart...
11:11:44-  Goodbye.
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1
11:11:44-  
11:11:44-  running
11:11:44-  running1

关闭心脏。。。在告诉gui关闭时调用。所以我不太确定这里发生了什么,但这就是添加了Join()调用的输出。在


Tags: 方法代码脚本stringscriptargsthisprocess
2条回答

你能把系统stdout.flush()在python脚本中打印某些内容或打印一些额外的新行之后。没有得到任何输出的原因可能是python3的stdout缓冲区。在

我没看到剧本_线程。连接()打电话。我怀疑C#进程在python进程打印第一行之前就结束了。在

试试这个:

public PythonScript (string filePathDir, string args, Action<string> write)
{
    this.filePathDir = filePathDir;
    this.args = args;
    this.write = write;

    script_thread = new Thread (Run);
    script_thread.Start ();
    script_thread.Join ();  // Wait for the thread to terminate.
}

相关问题 更多 >

    热门问题