如何确定通过os.system启动的进程的pid [英] How to determine pid of process started via os.system

查看:886
本文介绍了如何确定通过os.system启动的进程的pid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个程序启动多个子进程,即模块foo.py启动bar.py的多个实例.

I want to start several subprocesses with a programm, i.e. a module foo.py starts several instances of bar.py.

由于有时需要手动终止进程,因此我需要进程ID来执行kill命令.

Since I sometimes have to terminate the process manually, I need the process id to perform a kill command.

即使整个设置很肮脏",但是如果通过os.system启动该进程,是否还有一种很好的pythonic方式来获取进程?pid?

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?

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:

import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")

推荐答案

os.system返回退出代码.它不提供子进程的pid.

os.system return exit code. It does not provide pid of the child process.

使用 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.

要终止该过程,可以使用 terminate 方法或 kill . (无需使用外部kill程序)

To terminate the process, you can use terminate method or kill. (No need to use external kill program)

proc.terminate()

这篇关于如何确定通过os.system启动的进程的pid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆