2

I'm trying:

import commands
print commands.getoutput("ps -u 0")

But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND

nothing more

Vasil
  • 36,468
  • 26
  • 90
  • 114

6 Answers6

8

This works on Mac OS X 10.5.5. Note the capital -U option. Perhaps that's been your problem.

import subprocess
ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE)
print ps.stdout.read()
ps.stdout.close()
ps.wait()

Here's the Python version

Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 1
    This isn't going to be very cross-platform. ps options on Linux/Unix are going to be different, and not exist at all on Windows. – slacy Jun 07 '12 at 18:51
6

If the OS support the /proc fs you can do:

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

A cross-platform solution (linux, freebsd, osx, windows) is by using psutil:

>>> import psutil
>>> psutil.pids()
[1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444]    
>>>
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
5

The cross-platform replacement for commands is subprocess. See the subprocess module documentation. The 'Replacing older modules' section includes how to get output from a command.

Of course, you still have to pass the right arguments to 'ps' for the platform you're on. Python can't help you with that, and though I've seen occasional mention of third-party libraries that try to do this, they usually only work on a few systems (like strictly SysV style, strictly BSD style, or just systems with /proc.)

Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
1

I've tried in on OS X (10.5.5) and seems to work just fine:

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

etc.

Python 2.5.1

Tisho
  • 8,320
  • 6
  • 44
  • 52
Dana
  • 32,083
  • 17
  • 62
  • 73
1

any of the above python calls - but try 'pgrep

Bill
  • 11
  • 1
0

It works if you use os instead of commands:

import os
print os.system("ps -u 0")
Tisho
  • 8,320
  • 6
  • 44
  • 52
jmissao
  • 655
  • 1
  • 6
  • 15
  • os.system() doesn't give you the output, the output is just printed to the screen. os.system() returns the process exit status, which you'll see as a trailing '0' in the output. – Thomas Wouters Oct 01 '08 at 23:52