这是后续这个问题 https://stackoverflow.com/questions/17395243/printing-stdout-in-realtime-from-subprocess,但如果我想传递一个参数stdin
to subprocess
,如何实时获取输出?这就是我目前所拥有的;我也尝试更换Popen
with call
来自subprocess
模块,这只会导致脚本挂起。
from subprocess import Popen, PIPE, STDOUT
cmd = 'rsync --rsh=ssh -rv --files-from=- thisdir/ servername:folder/'
p = Popen(cmd.split(), stdout=PIPE, stdin=PIPE, stderr=STDOUT)
subfolders = '\n'.join(['subfolder1','subfolder2'])
output = p.communicate(input=subfolders)[0]
print output
在前一个问题中我不必通过stdin
我被建议使用p.stdout.readline
,那里没有空间可以输送任何东西stdin
.
附录:这适用于传输,但我仅在最后看到输出,我想在传输发生时查看传输的详细信息。
为了实时从子进程中获取标准输出,您需要准确地决定您想要什么行为;具体来说,您需要决定是要逐行处理输出还是逐个字符处理输出,以及是否要在等待输出时阻塞或能够在等待时执行其他操作。
看起来对于您的情况来说,以行缓冲方式读取输出可能就足够了,阻塞直到每个完整的行进入,这意味着由subprocess
足够好:
p = subprocess.Popen(some_cmd, stdout=subprocess.PIPE)
# Grab stdout line by line as it becomes available. This will loop until
# p terminates.
while p.poll() is None:
l = p.stdout.readline() # This blocks until it receives a newline.
print l
# When the subprocess terminates there might be unconsumed output
# that still needs to be processed.
print p.stdout.read()
如果您需要写入进程的标准输入,只需使用另一个管道:
p = subprocess.Popen(some_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
# Send input to p.
p.stdin.write("some input\n")
p.stdin.flush()
# Now start grabbing output.
while p.poll() is None:
l = p.stdout.readline()
print l
print p.stdout.read()
Pace另一个答案是,不需要间接通过文件来将输入传递给子进程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)