关于subprocess:尝试通过Python解析正在运行的进程时出错

Error while trying to parse running processes through Python

我尝试用子进程python模块解析我的计算机(debian OS)中正在运行的程序。这是我的代码:

1
2
3
4
5
6
7
8
9
10
import subprocess

cmd ="ps -A" # Unix command to get running processes

runningprox = subprocess.check_output(cmd) #returns output as byte string

rpstring = runningprox.decode("utf-8")
#converts byte string to string and puts it in a variable

print(rpstring)

但是,当我运行代码时,会收到以下错误消息:

Traceback (most recent call last): File"ratalert.py", line 6, in

runningprox = subprocess.check_output(cmd) #returns output as byte string File"/usr/local/lib/python3.6/subprocess.py", line 336, in
check_output
**kwargs).stdout File"/usr/local/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process: File"/usr/local/lib/python3.6/subprocess.py", line 707, in init
restore_signals, start_new_session) File"/usr/local/lib/python3.6/subprocess.py", line 1333, in _execute_child
raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ps -A'

我不明白为什么会收到这个错误消息。考虑到'ps-a'既不是一个文件,也不是一个目录,而是我作为字符串放入变量中的unix命令。

我怎么修这个?谢谢您。


subprocess.check_output函数需要一个包含命令及其参数的列表,如下所示:

1
runningprox = subprocess.check_output(['ps', '-A'])

否则,它将把您传递的字符串视为单个命令,并查找名为ps -A的可执行文件,包括空格和all。

您可以使用shlex进行拆分,就像shell那样:

1
2
3
4
import shlex, subprocess

cmd = 'ps -A'
runningprox = subprocess.check_output(shlex.split(cmd))