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

时间:2015-08-04 22:07:45

标签: c# python linux process streamreader

我正在通过我的c#程序通过Process类运行一个简单的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:在回答我尝试的答案时,我在script_thread.Join()构造函数的其余代码下添加了PythonScript调用。这是更新后的代码:

    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 ();
        Console.WriteLine ("JOINED");
    }

我还添加了一个对控制台输出的调用,确实指示线程何时加入,永远不会输出。尝试此代码时,我的GUI窗口永远不会出现。但是我有一个WAS写入的日志系统,这是我应该进入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()调用后的输出结果。

2 个答案:

答案 0 :(得分:1)

你可以在你的python脚本中打印一些内容之后再输入sys.stdout.flush(),或者打印一些额外的新行。你没有获得任何输出的原因可能是因为python3的stdout缓冲区。

答案 1 :(得分:0)

我没有看到script_thread.Join()调用。我怀疑在python进程打印第一行之前C#进程正在完成。

试试这个:

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.
}