我认为在 python 中实现单例模式的一种简单方法是通过类属性:
import subprocess
class ProcessManager(object):
__PROCESS = None;
@staticmethod
def set_process(args):
# Sets singleton process
if __PROCESS is None:
p = subprocess.Popen(args)
ProcessManager.__PROCESS = p;
# else: exception handling
@staticmethod
def kill_process():
# Kills process
if __PROCESS is None:
# exception handling
else:
ProcessManager.__PROCESS.kill()
然后你可以通过以下方式使用这个类:
from my_module import ProcessManager
my_args = ...
ProcessManager.set_process(my_args)
...
ProcessManager.kill_process()
笔记:
- 负责
ProcessManager
创建过程,与结束对称
- 我没有足够的多线程知识来知道这是否适用于多线程模式