[英]Executing commandline commands from Python using subprocess module
I am trying to use the subprocess module
in python and trying to fetch the process id
of firefox
我正在尝试在python中使用
subprocess module
process id
subprocess module
并尝试获取firefox
的process id
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? 我想我正在执行的命令行参数的
pid
。我做错什么了吗? I confirmed that it is not the same using the ps aux | grep firefox
我确认使用
ps aux | grep firefox
是不一样的ps aux | grep firefox
ps aux | grep firefox
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. 如果使用
shell=True
pid,则将获得启动的Shell的pid,而不是所需进程的pid,尤其是当您使用&
将进程发送到后台时。
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. 您应该使用提供参数的长(列表)形式,不带
&
,因为如果将其与输出重定向结合使用,这毫无意义。
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. 但是,如果firefox已经在运行,则该方法也不起作用,因为在这种情况下,firefox将使用某些IPC来告诉现有进程打开新窗口,然后终止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.