2
我在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:無法發送輸入後開始通信」