Only first subprocess.Popen(…, stdin=f) in a loop works correctly

梦想与她 提交于 2019-12-01 14:57:41

The problem here is that once your file has been read once, the pointer is at the end of the file, so there's nothing left to read (so the second time you pass stdin=f for the same file, what's left is just empty).

Invert your inner and outer loops to reopen the file once every time you want to use it:

for c in computer:
    with open(cpu_script, "rb") as f:
        process = subprocess.Popen(["ssh", "-X", "-l", usr, c, "python3 -u -"],
                                   stdin=f, stdout=subprocess.PIPE)
        out = process.communicate()[0]

...or rewind back to the beginning between inner loops using the seek() function:

with open(cpu_script, "rb") as f:
    for c in computer:
        f.seek(0)   ### <- THIS RIGHT HERE
        process = subprocess.Popen(["ssh", "-X", "-l", usr, c, "python3 -u -"],
                                   stdin=f, stdout=subprocess.PIPE)
        out = process.communicate()[0]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!