这是this question的后续操作,但是如果我想将参数传递给stdin
到subprocess
,如何实时获取输出?这就是我目前所拥有的;我还尝试用subprocess
模块中的call
替换Popen
,这只会导致脚本挂起。
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
。
附录:这对传输有效,但我只在最后看到输出,我想在传输过程中看到传输的细节。
如果在开始读取输出之前传递了所有输入,如果是“实时”,则表示子进程刷新其stdout缓冲区时:
我想是这样的
使用迭代器将基本上返回实时结果。。
为了向stdin发送输入,您需要
这类似于
请参阅阿尔卑斯山答案,以便更好地传递到标准输入
为了实时地从子流程中获取stdout,您需要准确地决定您想要什么行为;具体地说,您需要决定是逐行处理输出还是逐字处理输出,以及您是希望在等待输出时阻塞还是能够在等待时执行其他操作。
看起来,以行缓冲方式读取输出可能就足够了,阻塞直到每个完整的行进入,这意味着
subprocess
提供的便利函数足够好:如果需要写入进程的stdin,只需使用另一个管道:
另一个答案是,不需要通过文件间接地将输入传递给子流程。
相关问题 更多 >
编程相关推荐