c#和python_C#和Python之间的进程间通信

1586010002-jmsa.png

I can understand that there has been a lot of questions on this topic but none of them could really solve my problem. So here I have presented my code, and I want my mistakes to be pointed out here.

I have a program written in C# which shall call a python executable/file. The first requirement is that I have pass one argument to the python file via the input stream. This I could do. The real problem I am facing now is that, I have to see whether my python file is printing "Please enter argument_x", I have to read this output in my C# code and check if it is argument_x, then only write the argument value in the input stream. Below are the code snippets for C# and Python.

The C# code is as follows:

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();

}

}

}

The python program in mytestpython.py file looks like this:

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()

Please help me out, as I feel I have written 90% of the code correctly with a minor mistake somewhere in between. Thanks in advance for your help.

解决方案

When you do myProcess.StandardOutput.ReadToEnd();, it tries to read to the end of the stdout of your Python program, meaning it will wait for the Python program to finish executing and close its stdout stream, which it never does because it's waiting for input from your C# program. This results in a deadlock.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值