Linux 如何确定通过 os.system 启动的进程的 pid
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20218570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine pid of process started via os.system
提问by Sebastian Werk
I want to start several subprocesses with a programm, i.e. a module foo.py
starts several instances of bar.py
.
我想用一个程序启动几个子进程,即一个模块foo.py
启动bar.py
.
Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.
由于有时我必须手动终止进程,因此我需要进程 ID 来执行 kill 命令。
Even though the whole setup is pretty “dirty”, is there a good pythonic way to obtain a process' pid
, if the process is started via os.system
?
即使整个设置非常“脏” pid
,如果进程是通过 启动的,是否有一种很好的pythonic方法来获取进程' os.system
?
foo.py:
foo.py:
import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))
bar.py:
bar.py:
import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
采纳答案by falsetru
os.system
return exit code. It does not provide pid of the child process.
os.system
返回退出代码。它不提供子进程的pid。
Use subprocess
module.
使用subprocess
模块。
import subprocess
import time
argument = '...'
proc = subprocess.Popen(['python', 'bar.py', argument], shell=True)
time.sleep(3) # <-- There's no time.wait, but time.sleep.
pid = proc.pid # <--- access `pid` attribute to get the pid of the child process.
To terminate the process, you can use terminate
method or kill
. (No need to use external kill
program)
要终止进程,您可以使用terminate
method 或kill
。(无需使用外部kill
程序)
proc.terminate()
回答by Tobias W?rre
You could use os.forkpty()
instead, which, as result code, gives you the pid and fd for the pseudo terminal. More documentation here: http://docs.python.org/2/library/os.html#os.forkpty
您可以改用os.forkpty()
它,作为结果代码,它为您提供伪终端的 pid 和 fd。更多文档在这里:http: //docs.python.org/2/library/os.html#os.forkpty
回答by Damaris
Sharing my solution in case it can help others:
分享我的解决方案,以防它可以帮助他人:
I took the info from this page to run a fortran exe in the background. I tried to use os.forkpty to get the pid of it, but it didnt give the pid of my process. I cant use subprocess, because I didnt find out how it would let me run my process on the background.
我从这个页面获取信息在后台运行一个 fortran exe。我尝试使用 os.forkpty 来获取它的 pid,但它没有给出我的进程的 pid。我不能使用子进程,因为我没有发现它如何让我在后台运行我的进程。
With help of a colleague I found this:
在同事的帮助下,我发现了这个:
exec_cmd = 'nohup ./FPEXE & echo $! > /tmp/pid'
os.system(exec_cmd)
In case of wanting to append pids to the same file, use double arrow.
如果想要将 pid 附加到同一个文件,请使用双箭头。