【问题标题】:python pipe only stdin,out once, how to do twice or more timepython管道只有标准输入,输出一次,如何做两次或更多时间
【发布时间】:2017-01-13 05:43:06
【问题描述】:

成功的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()

调用.py

import sys

getMsg = raw_input()
print getMsg

但我想要两次或更长时间的标准输入,输出

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

这个来源有什么问题

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

import sys

getMsg = raw_input()
print getMsg

getMsg2 = raw_input()
print getMsg2

:D

【问题讨论】:

    标签: python pipeline


    【解决方案1】:

    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()
    

    请注意,至少当您的操作系统是 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)
    

    【讨论】:

    • 谢谢效果很好,我不知道为什么这个在窗口中可能使用 git bash?
    • Windows 似乎不需要 shebang(它可能甚至不被 Windows 识别),它使用此类文件的默认程序(至少这是我使用 node.js 的经验)
    【解决方案2】:

    当您说“但我想要两次或更多时间 stdin,out”时,我不确定您的真正意思。

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

    【讨论】:

    • 对不起,我不擅长 Linux/Unix 系统。我不明白。
    • Linux/UNIX 中存在此限制的任何原因?这使得无法从输入中读取,例如input(...) 使用 python)仅仅是因为您很早就从 STDIN 读取了一些数据。为什么会有这个限制?我在这里也有同样的痛苦stackoverflow.com/questions/63419843/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2015-01-05
    相关资源
    最近更新 更多