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

查看:51
本文介绍了如何确定通过 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 启动的,是否有一种很好的 Python 方法来获取进程的 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 模块.

Use subprocess module.

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天全站免登陆