gpt4 book ai didi

c# - C#和Python之间的进程间通信

转载 作者:行者123 更新时间:2023-11-28 20:09:20 29 4
gpt4 key购买 nike

我能理解有很多关于这个主题的问题,但没有一个能真正解决我的问题。所以在这里我展示了我的代码,我希望在这里指出我的错误。

我有一个用 C# 编写的程序,它将调用 python 可执行文件/文件。第一个要求是我已经通过输入流将一个参数传递给 python 文件。这是我能做到的。我现在面临的真正问题是,我必须查看我的 python 文件是否正在打印“请输入 argument_x”,我必须在我的 C# 代码中读取此输出并检查它是否为 argument_x,然后只将参数值写入输入流。以下是 C# 和 Python 的代码片段。

C#代码如下:

using System;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//Create a new process object
Process myProcess = new Process();

//Provide the start information for the process
myProcess.StartInfo.FileName = "python.exe";
myProcess.StartInfo.Arguments = "mytestpython.py";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.StartInfo.RedirectStandardOutput = true;

StreamReader myStreamReader;
StreamWriter myStreamWriter;

//Invoke the process from current process
myProcess.Start();

myStreamReader = myProcess.StandardOutput;

//Read the standard output of the spawned process.
string myString = myProcess.StandardOutput.ReadToEnd();
Console.WriteLine(myString);

if (myString.Contains("argument_x"))
{
myStreamWriter = myProcess.StandardInput;
String argument = "argument_value";
myStreamWriter.WriteLine(argument);
}

myProcess.WaitForExit();
myStreamWriter.Close();
myStreamReader.Close();
myProcess.Close();
}
}
}

mytestpython.py 文件中的 python 程序如下所示:

import sys
import getpass
prompt_string = "Please enter argument_x"
if sys.stdin.isatty():
reqd_arg = getpass.getpass(prompt=prompt_string)
else:
print(prompt_string)
reqd_arg = sys.stdin.readline().rstrip()

请帮助我,因为我觉得我已经正确地编写了 90% 的代码,中间有一个小错误。预先感谢您的帮助。

最佳答案

当您执行 myProcess.StandardOutput.ReadToEnd(); 时,它会尝试读取到 Python 程序标准输出的末尾,这意味着它将等待 Python 程序完成执行并关闭它的 stdout 流,它永远不会这样做,因为它正在等待来自 C# 程序的输入。这会导致死锁。

关于c# - C#和Python之间的进程间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940068/

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