进程间通信Python

问题描述:

我在Python中编写脚本,该脚本应该与软件 “ConsoleApplication.exe”通信(写在C中);这个最后一个开始等待从他的“标准输入”中输入一个固定的 长度命令(5字节),并在 上生成(在2-3秒后)他的“标准输出”输出,我应该在我的Python脚本中读取它。进程间通信Python

//This is the "ConsoleApplication.c" file 
#include <stdio.h> 
#include <function.h> 

char* command[5]; 
int main() 
{ 
while(1) 
{ 

scanf("%s\n", &command); 
output = function(command); 
print("%s\n", output); 

} 
} 
#this is Python code 

import subprocess 
#start the process 
p = subprocess.Popen(['ConsoleApplication.exe'], shell=True, stderr=subprocess.PIPE) 
#command to send to ConsoleApplication.exe 
command_to_send = "000648" 
#this seems to work well but I need to send a command stored into a buffer and if Itry 
#to use sys.stdout.write(command_to_send)nothing will happen. The problem seem that 
#sys.stdout.write expect an object I/O FILE 
while True: 
    out = p.stderr.read(1) 
    if out == '' and p.poll() != None: 
     break 
    if out != '': 
     sys.stdout.write(out) 
     sys.stdout.flush() 

有什么建议?我该如何解决它?

我试图用

stdout = p.communicate(input='test\n')[0] 

但是我得到以下运行时错误: “类型错误:‘STR’不支持缓冲区接口” 我也试过这个

from subprocess import Popen, PIPE, STDOUT 


p = Popen(['ConsoleApplication.exe'], stdout=PIPE, stdin=PIPE, stderr=PIPE) 

out, err = p.communicate(input='00056\n'.encode()) 
print(out) 
out, err = p.communicate(input='00043\n'.encode()) 
print(out) 

但我得到这个错误: “ValueError:无法发送输入后开始通信”

看起来l IKE这个问题有解决方案

Python - How do I pass a string into subprocess.Popen (using the stdin argument)?

使用Popen.communicate()方法