python-循环中只有第一个subprocess.Popen(…,stdin = f)可以正常工作

我的主要目标是获取与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)

现在这是我从这些输入中得到的结果:

>> 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''

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

我怀疑我的第一个进程没有很好地“关闭”,因此我尝试在input(out)之后添加一个process.wait()或process.kill(),但无济于事.

预先感谢您的帮助 !

编辑: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'')

解决方法:

这里的问题是,一旦文件被读取一次,指针就位于文件的末尾,因此没有什么可读取的(因此,第二次将同一个文件传递给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]
上一篇:使用Python跟踪流程状态


下一篇:python-检查子进程调用是否成功执行