如何防止subprocess.call打印返回代码?

问题描述 投票:-1回答:1

当使用subprocess.call(cmd,shell = True)时,如何阻止该零点悬挂在此print语句的末尾?

print("The top five memory consumers on the system are:")
print(subprocess.call('ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6', shell=True))

输出:

The top five memory consumers on the system are:
  PID  PPID CMD                         %MEM %CPU
  807     1 /usr/bin/python -Es /usr/sb  3.1  0.0
  615   555 /sbin/dhclient -d -q -sf /u  3.0  0.0
 1500   917 python                       1.7  0.0
 9921   917 python ./dkap_sysinfo.py     1.7  0.0
  556     1 /usr/sbin/rsyslogd -n        1.3  0.0
0

^问题孩子

python subprocess
1个回答
1
投票

您可以使用subprocess.check_output()而不是subprocess.call()

import subprocess

print("The top five memory consumers on the system are:")

cmd = "ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6"
result = subprocess.check_output(cmd, shell=True).decode()

lines = result.split("\n")
for line in lines:
    print(line)

另请注意,check_output()的结果是一个类似字节的对象,因此如果要将其作为字符串使用,则必须在其上调用.decode()

© www.soinside.com 2019 - 2024. All rights reserved.