我正在用Python编写一个应该与软件通信的脚本 “ConsoleApplication.exe”(用C写的);这最后一次开始等待修复 lenght命令(5个字节)来自他的“stdin”并生成(2-3秒后) 他的“stdout”是我应该在我的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'不支持缓冲区接口” 我也试过这个
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:开始通信后无法发送输入”
答案 0 :(得分:0)
看起来这个问题有你的解决方案
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
使用Popen.communicate()方法