简体   繁体   English

使用子流程模块从Python执行命令行命令

[英]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并尝试获取firefoxprocess 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.

相关问题 Python:无法通过使用子进程模块在另一个命令行应用程序中进行读取/写入 - Python: cannot read / write in another commandline application by using subprocess module 从 python 执行子进程 - executing a subprocess from python 无法使用python子进程模块运行带有*的shell命令 - Unable to run shell commands with * using python subprocess module 使用模块从python执行OS命令 - executing OS commands from python using modules 在Python中使用子流程模块 - Using the subprocess module in Python SVN 命令不通过 Python 子进程模块接受 - SVN commands not accepted via Python subprocess module ModuleNotFoundError: No module named 'selenium' error 从命令行执行 Selenium Python 脚本 - ModuleNotFoundError: No module named 'selenium' error executing Selenium Python script from commandline 如何在子进程中使用python在单个会话中执行多个命令的子进程中使用变量 - How to use variables in subprocess executing multiple commands in single session using python Python子进程创建一个新窗口并继续在其中执行命令 - Python subprocess make a new window and keep executing commands in it 如何使用Python的子进程模块在终端中执行两个命令? - How can I execute two commands in terminal using Python's subprocess module?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM