getting properly one subprocess output
Nobody
nobody at nowhere.com
Thu Nov 19 11:40:10 EST 2009
On Thu, 19 Nov 2009 06:21:09 -0800, Bas wrote:
> Below is the script I use to automatically kill firefox if it is not
> behaving, maybe you are looking for something similar.
> lines = os.popen('ps ax|grep firefox').readlines()
This isn't robust. It will kill any process with "firefox" anywhere in its
command line, which isn't limited to processes which are actually running
the firefox web browser.
> lines = [line for line in lines if 'grep' not in line]
This line excludes one such process, but there may be others.
A more robust approach would be to check for the string in the command
name (i.e. argv[0]) rather than the complete command-line, by using e.g.
"ps ... -o pid,comm":
lines = os.popen('ps axheo pid,comm').readlines()
lines = [line.strip().split(' ', 1) for line in lines]
lines = [(int(pid), cmd) for pid, cmd in lines if 'firefox' in cmd]
Better still would be to check that "firefox" is a complete word, not part
of one, e.g. with the regular expression r"\bfirefox\b". This would match
"firefox", "/usr/bin/firefox", "firefox-bin", etc, but not e.g.
"kill_firefox", e.g.:
lines = [(int(pid), cmd) for pid, cmd in lines if re.search(r'\bfirefox\b', cmd)]
That's about as good as you can get without using non-portable mechanisms
such as /proc/*/exe.
More information about the Python-list
mailing list