gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:17:43 25 4
gpt4 key购买 nike

我编写了一个简单的程序来捕获并执行命令行 Python 脚本,但有一个问题。尽管我的程序捕获了标准输出,但传递给 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)

关于c# - 某些 Python 命令未在 Stdout 中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2321868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com