Run a program from python, and have it continue to run after the script is killed(从python运行程序,并在脚本被杀死后继续运行)
问题描述
我试过这样运行:
subprocess.Popen(['nohup', 'my_command'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'))
如果父脚本正常退出,这会起作用,但如果我终止脚本 (Ctrl-C),我的所有子进程也会被终止.有没有办法避免这种情况?
This works if the parent script exits gracefully, but if I kill the script (Ctrl-C), all my child processes are killed too. Is there a way to avoid this?
我关心的平台是 OS X 和 Linux,使用 Python 2.6 和 Python 2.7.
The platforms I care about are OS X and Linux, using Python 2.6 and Python 2.7.
推荐答案
在 Unix 系统上执行此操作的通常方法是,如果您是父级,则分叉并退出.看看 os.fork()
.
The usual way to do this on Unix systems is to fork and exit if you're the parent. Have a look at os.fork()
.
这是一个完成这项工作的函数:
Here's a function that does the job:
def spawnDaemon(func):
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details (ISBN 0201563177)
try:
pid = os.fork()
if pid > 0:
# parent process, return and keep running
return
except OSError, e:
print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
os.setsid()
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
sys.exit(1)
# do stuff
func()
# all done
os._exit(os.EX_OK)
这篇关于从python运行程序,并在脚本被杀死后继续运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从python运行程序,并在脚本被杀死后继续运行


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01