我正在用Python语言编写一个脚本,它应该与软件“ConsoleApplication.exe”(用C编写)进行通信;最后一个脚本启动后,等待来自他的"stdin“的固定长度的命令(5个字节),并在他的"stdout”上生成( 2-3秒后)我应该在我的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] 但我在运行时收到以下错误:"TypeError:'str‘不支持buffer接口“我也尝试了一下
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: Cannot send input after starting“
发布于 2014-12-07 20:39:16
看起来这个问题有你的答案
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
使用Popen.communicate()方法
https://stackoverflow.com/questions/27342619
复制相似问题