我正在尝试:
import commands
print commands.getoutput("ps -u 0")
但它在os x上不起作用。 os而不是命令给出相同的输出: USER PID%CPU%MEM VSZ RSS TT STAT STARTED TIME COMMAND
不再是
答案 0 :(得分:8)
适用于Mac OS X 10.5.5。请注意大写 -U 选项。也许那是你的问题。
import subprocess
ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE)
print ps.stdout.read()
ps.stdout.close()
ps.wait()
这是Python版本
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
答案 1 :(得分:6)
如果操作系统支持/ proc fs,你可以这样做:
>>> import os
>>> pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
>>> pids
[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]
>>>
跨平台解决方案(linux,freebsd,osx,windows)使用psutil:
>>> import psutil
>>> psutil.pids()
[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]
>>>
答案 2 :(得分:5)
commands
的跨平台替代品为subprocess
。请参阅subprocess module documentation。 “替换旧模块”部分包括how to get output from a command。
当然,你仍然需要为你所在的平台传递正确的参数'ps'。 Python无法帮助你,虽然我偶尔会看到试图这样做的第三方库,但它们通常只适用于少数几个系统(如严格的SysV风格,严格的BSD风格,或只是的/ proc。)
答案 3 :(得分:1)
我已经尝试过OS X(10.5.5)并且似乎工作得很好:
print commands.getoutput("ps -u 0")
UID PID TTY TIME CMD
0 1 ?? 0:01.62 /sbin/launchd
0 10 ?? 0:00.57 /usr/libexec/kextd
等
Python 2.5.1
答案 4 :(得分:1)
任何上述python调用 - 但请尝试'pgrep
答案 5 :(得分:0)
如果使用os而不是命令,它可以工作:
import os
print os.system("ps -u 0")