![](/img/trans.png)
[英]Gently kill a process created with Python's subprocess.Popen() in Windows
[英]Name process when creating it with python's subprocess.Popen()
我正在使用 python 的 subprocess.Popen() 一次運行多個子進程。 每次進程終止時,我都想在 shell 上打印類似的內容: process ABC has been terminated
ABC 是我自己給進程命名的名稱。 我想也許有一種方法可以使用這樣的代碼來實現這一點: process.name()
有沒有辦法通過 subprocess.Popen() 做到這一點?
使用 subprocess 沒有可移植的方法,您可以結合使用另一個subprocess
,您可以查看https://github.com/dvarrazzo/py-setproctitle庫。
使用該模塊,您可以命名進程標題,然后訪問它並輕松打印所需的 output。
這是您使用 inheritance 的教科書示例。
import subprocess
class NamedPopen(subprocess.Popen):
"""
Like subprocess.Popen, but returns an object with a .name member
"""
def __init__(self, *args, name=None, **kwargs):
self.name = name
super().__init__(*args, **kwargs)
fred = NamedPopen('sleep 11; echo "yabba dabba doo"', shell=True, name="fred")
barney = NamedPopen('sleep 22; echo "hee hee, okay fred"', name="barney", shell=True)
print('... stay tuned ...')
fred.wait()
barney.wait()
請注意不要選擇父 class 用於其他用途的屬性名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.