我有一个从Haskell编译的简单的.exe文件,它只输出到stdout它收到的所有东西到stdin:
module Main where
main = do
command <- getLine
putStrLn command
main我有一个Python文件,它试图向子进程发送两行代码:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['main.exe'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
def send_command(arg):
print("Sending command: "+arg)
response = p.communicate(input=arg)[0].decode()
print("Response: "+response+"\n")
return response
send_command("Test1")
send_command("Test2")它第一次工作,但第二次不起作用,显然是因为它认为输入已经完成:
Sending command: Test1
Response: Test1
main.exe: <stdin>: hGetLine: end of file
Sending command: Test2
Traceback (most recent call last):
File ".\test.py", line 12, in <module>
send_command("Test2")
File ".\test.py", line 7, in send_command
response = p.communicate(input=arg)[0].decode()
File "C:\Python27\lib\subprocess.py", line 483, in communicate
return self._communicate(input)
File "C:\Python27\lib\subprocess.py", line 722, in _communicate
self.stdin.write(input)
ValueError: I/O operation on closed file我不知道错误是Python还是Haskell;从Python调用的其他子进程和从命令行调用时Haskell文件的工作方式相同,但它们只是拒绝一起工作。怎么解决这个问题?
编辑:
我将communicate替换为直接读\写:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['main.exe'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
def send_command(arg):
print("Sending command: "+arg)
p.stdin.write(arg+"\n")
response = p.stdout.readline().decode()
print("Response: "+response+"\n")
return response
send_command("Test1")
send_command("Test2")并确保(以防万一) .exe正确终止行:
module Main where
main = do
command <- getLine
putStrLn (command ++ "\n")
main现在这个程序就停止了,现在什么也不做了:
Sending command: Test1我应该以某种方式“冲洗”输入吗?
发布于 2019-08-29 10:56:24
下面是您正在调用的subprocess.Popen.communicate函数的文档:
Popen.communicate(input=None,timeout=None) 与进程交互:将数据发送到stdin。从stdout和stderr读取数据,直到文件结束.等待进程终止。
(我的重点)。
如果您不想要p.stdin所做的所有其他事情,您可以直接写到p.stdout并从p.stdout中读取。
我不知道是Python还是Haskell的错
这不是作为批评,而是一个有用的提示:错误在于谁没有阅读他们调用的函数的文档。这是免费的,读吧!
https://stackoverflow.com/questions/57708589
复制相似问题