如何防止subprocess.call打印返回码?
当使用subprocess.call(cmd,shell = True)时,我该如何停止从打印语句末尾悬挂零点?如何防止subprocess.call打印返回码?
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
^问题孩子
回答:
可以使用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()
如果你想使用它作为一个字符串。
以上是 如何防止subprocess.call打印返回码? 的全部内容, 来源链接: utcz.com/qa/260573.html