0

I am trying to use the subprocess module in python and trying to fetch the process id of firefox

cmd = "firefox &" 
fire = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, preexec_fn=os.setsid)
fire_task_procs = find_task(fire.pid)
print "fire_task_procs",fire_task_procs

I think I am getting the pid of the commandline argument that I am executing.. am I doing something wrong? I confirmed that it is not the same using the ps aux | grep firefox

2 Answers 2

2

If you use shell=True the pid you'll get ist that of the started shell, not that of the process you want, specially as you use & to send the process into background.

You should use the long (list) form of supplying the parameters, without &, as that makes little sense anyway if you combine it with output redirection.

2
  • If I don't use shell=True, I get the following error: Traceback (most recent call last): File "test.py", line 33, in <module> fire = subprocess.Popen(cmd, stdout=subprocess.PIPE, preexec_fn=os.setsid) File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
    – rnish
    Commented Apr 12, 2013 at 21:19
  • If you don't use shell=True and you pass the string "firefox &", you will get an error, because that's not a reasonable arg string. (Depending on your platform, this may ask firefox to open a file called &, or it may try to find a program named firefox &, neither of which is right.) But if you just drop the &, it is. And ideally, switch to an arg list. (As the docs say a few times, "Providing a sequence of arguments is generally preferred" when you're not using shell=True, especially on POSIX.) So, change cmd to ["firefox"].
    – abarnert
    Commented Apr 12, 2013 at 22:05
1

Don't use the shell, instead just use

subprocess.Popen(['firefox'], stdout=subprocess.PIPE, preexec_fn=os.setsid)

However, if firefox is already running then this will not work either since in this case firefox will use some IPC to tell the existing process to open a new window and then terminates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.