只有循环中的第一个subprocess.Popen(...,stdin = f)才能正常工作

时间:2018-06-14 21:46:48

标签: python python-3.x subprocess psutil

我的主要目标是获取Linux连接计算机列表的所有cpu费用。我一直在网上挣扎和搜索一段时间,但我必须错过一些因为找不到答案的东西。 所以我定义了一个cpu_script.py:

import psutil

print(psutil.cpu_percent(interval=1,percpu=True))

在我的主脚本中调用,该脚本位于同一文件夹中,其中包含:

import subprocess
import os
import numpy as np
import psutil

usr = "AA"
computer = ["c1", "c2", "c3"] #list of computer which cpu load is to be tested
cpu_script = os.path.join(os.getcwd(),"cpu_script.py")

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

现在这是我从这些input得到的:

>> c1 #first computer
>> <subprocess.Popen object at 0x7fd210aab358>
>> b'[1.0, 7.1, 0.0, 1.0, 2.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0]\n'
>> c2 #second computer
>> <subprocess.Popen object at 0x7fd210aab390>
>> b''
>> c3 #third computer
>> <subprocess.Popen object at 0x7fd210aab390>
>> b''

所以这是我的问题:为什么第二和第三个输出是空的?我怎么能得到它们?

我怀疑我的第一个流程没有“关闭”,所以我尝试在process.wait()之后添加process.kill()input(out),但无济于事。

提前感谢您的帮助!

编辑:subprocess.check_output()提供相同的输出。我还尝试了subprocess.run

with open(cpu_script,"rb") as f:
    for c in computer:
        input(c)
        process = subprocess.run(["ssh","-X",usr + "@" + c,"python3","-u","-"], stdin=f, stdout=subprocess.PIPE)
        input(out)

得到了:

>> c1 #first computer
>> CompletedProcess(args=['ssh', '-X', 'usr@c1', 'python3', '-u', '-'], returncode=0, stdout=b'[2.0, 1.0, 1.0, 2.9, 7.0, 0.0, 2.0, 1.0, 0.0, 0.0, 0.0, 1.0]\n')
>> c2 #second computer
>> CompletedProcess(args=['ssh', '-X', 'usr@c2', 'python3', '-u', '-'], returncode=0, stdout=b'')
>> c3 #third computer
>> CompletedProcess(args=['ssh', '-X', 'usr@c3', 'python3', '-u', '-'], returncode=0, stdout=b'')

1 个答案:

答案 0 :(得分:2)

这里的问题是,一旦你的文件被读了一次,指针就在文件的末尾,所以没有什么可以读的(所以你第二次为同一个文件传递stdin=f,那是什么的左边只是空的。)

每次要使用它时,反转内部和外部循环以重新打开文件:

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]

...或使用seek()函数回退到内部循环之间的开头:

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]