某些Python命令未在Stdout中捕获 - c#

我编写了一个简单的程序来捕获并执行命令行Python脚本,但是存在问题。尽管我的程序捕获了stdout,但传递给Python输入函数的文本并未写入我的程序。

例如:
Python脚本:

import sys

print("Hello, World!")
x = input("Please enter a number: ")
print(x)

print("This work?")

会写“你好,世界!”然后停下来。当我传递数字时,它将继续写“请输入数字:3”。到底是怎么回事?有什么办法吗?我的C#如下:

public partial class PyCon : Window
{
        public string strPythonPath;
        public string strFile;
        public string strArguments;
        private StreamWriter sw;

        public PyCon(string pythonpath, string file, string args)
        {
            strPythonPath = pythonpath;
            strFile = file;
            strArguments = args;

            InitializeComponent();

            Process p = new Process();

            p.StartInfo.FileName = strPythonPath;
            p.StartInfo.Arguments = "\"" + strFile + "\" " + strArguments;

            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);

            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            sw = p.StandardInput;
        }

        private void p_OutputDataReceived(object sendingProcess, DataReceivedEventArgs received) {
            if (!String.IsNullOrEmpty(received.Data)) {
                AppendConsole(received.Data);
            }
        }

        private void p_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs received) {
            if (!String.IsNullOrEmpty(received.Data)) {
                AppendConsole(received.Data);
            }
        }

        private void AppendConsole(string message) {
            if (!txtConsole.Dispatcher.CheckAccess()) {
                txtConsole.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate() { txtConsole.AppendText(message + "\n"); });
            } else {
                //Format text
                message = message.Replace("\n", Environment.NewLine);

                txtConsole.AppendText(message + "\n");   
            }
        }

        private void txtInput_KeyUp(object sender, KeyEventArgs e) {
            if (e.Key != Key.Enter) return;

            sw.WriteLine(txtInput.Text);

            txtInput.Text = "";


        }
    }

编辑:经过对该线程的大量研究和帮助,我得出的结论是,问题在于Python输入命令未调用C#DataReceivedEventHandler。除了脚本更改之外,可能没有其他解决方案。如果是这种情况,我将给出包含已接受更改的答案。谢谢大家的帮助!

参考方案

闻起来像Python I / O是行缓冲的,即等待CRLF然后立即发送整行。您可以尝试将其关闭(python -u myscript.py,或设置PYTHONUNBUFFERED环境变量),或使用以下方法解决该问题:

print("Hello, World!")
print("Please enter a number: ")
x = input()
print(x)

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

比较用户输入和关键词列表 - python

我想通过功能接收用户输入并将其与关键字列表进行比较,如果用户输入的任何单词与关键字匹配,则满足条件并中断循环。如果没有一个单词与关键字匹配,则控制台再次要求输入。我一直在处理此循环,或者不管是否遇到关键字都让它不断地要求输入,或者验证每个输入的单词。任何有关如何纠正它的建议将不胜感激。def validated_response(user_complaint…