[英]How to detach Python child process on Windows (without setsid)?
I'm migrating some process code to Windows which worked well on Posix. 我正在将一些过程代码迁移到在Posix上运行良好的Windows。 Very simply put: the code to launch a subprocess and immediately detach will not work because
setsid()
is not available: 简而言之:因为
setsid()
不可用,所以启动子进程并立即分离的代码将不起作用:
import os, subprocess, sys
p = subprocess.Popen([sys.executable, '-c', "print 'hello'"], preexec_fn=os.setsid)
I can remove the use of setsid
but then the child process ends when the parent ends. 我可以删除
setsid
的用法,但是当父进程结束时,子进程结束。
My question is how do I achieve the same effect as setsid
on Windows so that the child process lifetime is independent of the parent's? 我的问题是如何在Windows上实现与
setsid
相同的效果,以使子进程的生命周期独立于父进程的生命周期?
I'd be willing to use a particular Python package if one exists for this sort of thing. 我愿意使用一种特定的Python软件包(如果有)用于这种事情。 I'm already using
psutil
for example but I didn't see anything in it that could help me. 例如,我已经在使用
psutil
,但没有看到任何可以帮助我的东西。
RbMn's comment on my question is in fact the answer. RbMn对我的问题的评论实际上就是答案。 There is no need to detach because processes in Windows are always top-level objects.
不需要分离,因为Windows中的进程始终是顶级对象。 I tried this out with a sleeper task and it worked fine.
我通过卧铺任务尝试了一下,效果很好。
However as eryksun pointed out in the comments here, closing the console window WILL cause the child process to terminate. 但是,正如eryksun在此处的注释中指出的那样,关闭控制台窗口将导致子进程终止。 I also had some stability issues with Waitress and Popen on Windows that I think I've worked through by adding the following bit of code which sets some process creation flags and uses
close_fds
: 我在Windows上的Waitress和Popen中也遇到了一些稳定性问题,我认为我已经通过添加以下代码来解决这些问题,这些代码设置了一些进程创建标志并使用
close_fds
:
if 'nt' == os.name:
flags = 0
flags |= 0x00000008 # DETACHED_PROCESS
flags |= 0x00000200 # CREATE_NEW_PROCESS_GROUP
flags |= 0x08000000 # CREATE_NO_WINDOW
pkwargs = {
'close_fds': True, # close stdin/stdout/stderr on child
'creationflags': flags,
}
p = subprocess.Popen([sys.executable, '-c', cmd], **pkwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.