Reputation:
So I've got this to find out if a process is running or not:
os.system("ps aux | grep [my]process")
I use the square brackets so I don't get back the grep command too.
Altho when I try to do something like
'yes' if os.system("ps aux | grep [my]process") else 'no'
I always get no, even if in fact python print the line with the info of the process.
Pretty sure that there must be some sort of misunderstanding from my side...I assume that if the output of os.system is not zero, the expression resolve in true, so I should get 'yes'. But this does not happen at all, I get no, even if the process is there running, and the command return correctly the info about the process.
What am I doing wrong here?
Thanks!
Upvotes: 0
Views: 3185
Reputation: 304483
You have the logic the wrong way round. grep
is returning 0
when there are some matching lines
using the subprocess
module is a better idea anyway. You can get the output of ps aux
and examine it in your program. Although parsing the output of ps is always going to be fairly fragile
eg:
import subprocess
'yes' if 'myprocess' in subprocess.check_output(['ps','aux']) else 'no'
Upvotes: 5
Reputation: 2476
os.system returns exit status of the command executed. If the command is successful, it returns 0, or else non-zero number. Example:
>>> t=os.system("ls")
>>> t
0
>>> t=os.system("lsas")
sh: 1: lsas: not found
>>> t
32512
>>>
Upvotes: 2
Reputation: 1461
The output of os.system
is not what is printed on the screen.
On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.ù
http://docs.python.org/2/library/os.html#os.system
Upvotes: 3