如何使从Python调用的Haskell supprocess在一次使用后不关闭?

2024-06-02 09:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从Haskell编译的简单的.exe文件,它只是将接收到的所有内容打印到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文件时,它的其他子进程与预期的一样,当从命令行调用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

我是不是应该“刷新”输入?你知道吗


Tags: 文件sendhaskellmainresponsestdinargexe
1条回答
网友
1楼 · 发布于 2024-06-02 09:08:26

以下是您正在调用的^{}函数的文档:

Popen.communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

(我的重点)。你知道吗

如果你不想要其他的东西,你可以直接写到p.stdin然后从p.stdout读。你知道吗

I don't know if the fault lies with Python or Haskell

这不是批评,而是一个有用的提示:错误在于没有阅读他们调用的函数的文档的人。免费的,看吧!你知道吗

相关问题 更多 >