首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使从Python调用的Haskell suprocess在一次使用后不关闭?

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

Stack Overflow用户
提问于 2019-08-29 10:51:09
回答 1查看 147关注 0票数 0

我有一个从Haskell编译的简单的.exe文件,它只输出到stdout它收到的所有东西到stdin:

代码语言:javascript
复制
module Main where

main = do
  command <- getLine
  putStrLn command
  main

我有一个Python文件,它试图向子进程发送两行代码:

代码语言:javascript
复制
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")

它第一次工作,但第二次不起作用,显然是因为它认为输入已经完成:

代码语言:javascript
复制
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替换为直接读\写:

代码语言:javascript
复制
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正确终止行:

代码语言:javascript
复制
module Main where

main = do
  command <- getLine
  putStrLn (command ++ "\n")
  main

现在这个程序就停止了,现在什么也不做了:

代码语言:javascript
复制
Sending command: Test1

我应该以某种方式“冲洗”输入吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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的错

这不是作为批评,而是一个有用的提示:错误在于谁没有阅读他们调用的函数的文档。这是免费的,读吧!

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57708589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档