python - 如何确定通过 os.system 启动的进程的 pid

标签 python linux subprocess os.system

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

因为有时我必须手动终止进程,所以我需要进程 ID 来执行 kill 命令。

即使整个设置非常“脏”,如果进程是通过 os.system 启动的,是否有一个好的 pythonic 方法来获取进程的 pid

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。

使用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程序)

proc.terminate()

关于python - 如何确定通过 os.system 启动的进程的 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218570/

相关文章:

python - 如何让我的 discord.py 重写机器人向消息作者发送私有(private)消息

python - 二维列表生成 Python

c - 为什么 linux 编译的程序不能在 Windows 上运行

php - bintohex() 和 random_bytes() 函数在 Linux 上的 PHP 5.6 中未定义

python - 调试 subprocess.Popen 调用

python - 使用 Python 的子进程模块包装 Java 程序的问题

Python 子进程引用导致 fd 耗尽

python - 我可以从它的内存地址获取 Python 对象吗?

linux - 放入 shell 脚本时 [SED] 的奇怪行为

python - 如何更改 Jupyter Notebook 中的工作目录?