简体   繁体   English

使用 python 的 subprocess.Popen() 创建进程时命名进程

[英]Name process when creating it with python's subprocess.Popen()

I am using python's subprocess.Popen() to run multiple subprocesses at a time.我正在使用 python 的 subprocess.Popen() 一次运行多个子进程。 Each time a process is terminated, I want to print something like this to the shell: process ABC has been terminated ABC being a name that I give to the process myself.每次进程终止时,我都想在 shell 上打印类似的内容: process ABC has been terminated ABC 是我自己给进程命名的名称。 I thought maybe there is a way to achieve this using some code like this: process.name()我想也许有一种方法可以使用这样的代码来实现这一点: process.name()

Is there a way to do that through subprocess.Popen()?有没有办法通过 subprocess.Popen() 做到这一点?

There is no portable way to do so using subprocess , you could use another package in combination with it, you can check the https://github.com/dvarrazzo/py-setproctitle library.使用 subprocess 没有可移植的方法,您可以结合使用另一个subprocess ,您可以查看https://github.com/dvarrazzo/py-setproctitle库。

Using that module you can name a process title, and then access to it and print the desired output easily.使用该模块,您可以命名进程标题,然后访问它并轻松打印所需的 output。

This is a textbook example of what you use inheritance for.这是您使用 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()

Just take care to not pick an attribute name which the parent class uses for something else.请注意不要选择父 class 用于其他用途的属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM