我正在运行一个 etcd
进程,它会一直保持事件状态,直到您终止它。 (它不提供守护进程模式选项。)我想分离它以便继续运行更多 python。
我会在 shell 中做什么;
etcd & next_cmd
在整个互联网的热烈推荐下,我正在使用 python 的 sh
库。我不想深入研究 subprocess
或 Popen
,但我也没有找到使用它们的解决方案。
我想要的;
sh.etcd(detach=True)
sh.next_cmd()
或
sh.etcd("&")
sh.next_cmd()
不幸的是,detach
不是 kwarg,sh
将 "&"
视为 etcd
的标志。
我在这里遗漏了什么吗?执行此操作的好方法是什么?
最佳答案
要实现sh
的&
,避免cargo cult编程,直接使用subprocess
模块:
import subprocess
etcd = subprocess.Popen('etcd') # continue immediately
next_cmd_returncode = subprocess.call('next_cmd') # wait for it
# ... run more python here ...
etcd.terminate()
etcd.wait()
这会忽略异常处理和您关于“守护进程模式”的讨论(如果您想在 Python 中实现守护进程;请使用 python-daemon 。要将进程作为系统服务运行,请使用您的操作系统提供的任何内容或主管程序,例如作为 supervisord
)。
关于分离进程的Pythonic方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30519366/