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

删除回忆录丶 提交于 2019-12-02 22:17:03

问题


success python pipe stdin, out only one time this source

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

but I want twice or more time stdin, out

so update source but it's not work

What's wrong this source

main.py (update-not work)

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(update-not work)

import sys

getMsg = raw_input()
print getMsg

getMsg2 = raw_input()
print getMsg2

:D


回答1:


the output of call.py is buffered. so you have to flush() it to send to main.py.

#!/usr/bin/python2
import sys

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

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

Note that you need shebang #!/usr/bin/python2 at least when your OS is Linux (I don't know why OP's code works without shebang. Maybe some Windows magic ?).

Also you can use -u option not to buffer the output of python.

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



回答2:


When you say "but I want twice or more time stdin, out", I'm not sure what you really mean.

In a basic Linux/UNIX system, you have 1 - and only one - STDIN, STDOUT, and STDERR. Now, you can pipe things in and out, treating STDERR separately if you want, but you cannot just arbitrarily assign multiple inputs without setting up separate mechanisms (sockets, etc) to handle that within your program.



来源:https://stackoverflow.com/questions/41628070/python-pipe-only-stdin-out-once-how-to-do-twice-or-more-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!