python pipe only stdin,out 一次,如何做两次或更多次

python pipe only stdin,out once, how to do twice or more time

成功python管道标准输入,此源仅输出一次

main.py

import subprocess from subprocess import PIPE, STDOUT

player_pipe = subprocess.Popen(["source\call.py", 'arg1'], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=True)

player_pipe.stdin.write("Send Msg\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.kill()
player_pipe.wait()

call.py

import sys

getMsg = raw_input()
print getMsg

但我想要两次或更多时间 stdin, out

所以更新源,但它不起作用

这个来源有什么问题

main.py(更新无效)

import subprocess from subprocess import PIPE, STDOUT

player_pipe = subprocess.Popen(["source\call.py", 'arg1'], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=True)

player_pipe.stdin.write("Send Msg\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.stdin.write("Send Msg2\n")
get_stdout = player_pipe.stdout.readline()
print("[Get Msg]" + get_stdout)

player_pipe.kill()
player_pipe.wait()

call.py(更新无效)

import sys

getMsg = raw_input()
print getMsg

getMsg2 = raw_input()
print getMsg2

:D

当你说 "but I want twice or more time stdin, out" 时,我不确定你的真正意思。

在基本的 Linux/UNIX 系统中,您有 1 个 - 而且只有一个 - STDIN、STDOUT 和 STDERR。现在,您可以通过管道输入和输出内容,如果需要,可以单独处理 STDERR,但是您不能在不设置单独的机制(套接字等)的情况下任意分配多个输入来在您的程序中处理它。

call.py 的输出被缓冲。所以你必须 flush() 它发送到 main.py.

#!/usr/bin/python2
import sys

getMsg = raw_input()
print getMsg
sys.stdout.flush()

getMsg2 = raw_input()
print getMsg2
sys.stdout.flush()

请注意,至少当您的 OS 是 Linux 时,您需要 shebang #!/usr/bin/python2(我不知道为什么 OP 的代码在没有 shebang 的情况下也能工作。也许有些 Windows魔术?)。

您也可以使用 -u 选项不缓冲 python 的输出。

player_pipe = subprocess.Popen(["/usr/bin/python2","-u","./call.py"], stdin=PIPE,
     stdout=PIPE, stderr=STDOUT, shell=False)