简体   繁体   English

python运行外部程序并独立执行

[英]python run external program and continue its execution indepentently

How can i run an external program, let's say "Firefox", from my python script and make sure that its process will remain alive after the termination of my python script? 如何在我的python脚本中运行一个外部程序(例如“ Firefox”),并确保在我的python脚本终止后其进程仍然有效? I want to make it crossplatform if it's doable. 如果可行,我想使其跨平台。

There is no cross-platform way to do this with just the stdlib. 仅stdlib没有跨平台的方法可以做到这一点。 However, if you write code for POSIX and for Windows, that's usually good enough, right? 但是,如果您为POSIX和Windows编写代码,通常就足够了,对吗?

On Windows, you want to pass a creationflags argument. 在Windows上,您要传递creationflags参数。 Read the docs (both there and at MSDN ) and decide whether you want a console-detached process, a new-console process, or a new-process-group process, then use the appropriate flag. 阅读文档(在那里和在MSDN上 ),并确定是要控制台分离的进程,新控制台的进程还是新进程组的进程,然后使用适当的标志。 You may also want to set some of the flags in startupinfo ; 您可能还需要在startupinfo设置一些标志; again, MSDN will tell you what they mean. 再次, MSDN将告诉您它们的含义。

On POSIX, if you just want the simplest behavior, and you're using 3.2+, you want to pass start_new_session=True . 在POSIX上,如果您只想要最简单的行为,并且正在使用3.2+,则需要传递start_new_session=True In earlier Python versions, or for other cases, you want to pass a preexec_fn that allows you to do whatever daemonization you want. 在较早的Python版本中,或者在其他情况下,您希望传递一个preexec_fn ,它允许您执行所需的任何守护程序。 That could be as little as os.setsid() (what start_new_session does), or a whole lot more. 可能只有os.setsid()start_new_session做什么),或者更多。 See PEP 3143 -- Standard daemon process library for a discussion of all of the different things you might want to do here. 请参阅PEP 3143-标准守护进程进程库 ,以获取有关您可能要在此处执行的所有不同操作的讨论。

So, the simplest version is: 因此,最简单的版本是:

def launch_in_background(args):
    try:
        subprocess.CREATE_NEW_PROCESS_GROUP
    except AttributeError:
        # not Windows, so assume POSIX; if not, we'll get a usable exception
        p = subprocess.Popen(args, start_new_session=True)
    else:
        # Windows
        p = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)

If you're willing to go outside the stdlib, there are dozens of "shell-type functionality" libraries out there, many of which have some kind of "detach" functionality. 如果您愿意使用stdlib,那么这里有数十种“ shell类型功能”库,其中许多具有某种“分离”功能。 Just search shell , cli , or subprocess at PyPI and find the one you like best. 只需在PyPI上搜索shellclisubprocess进程,然后找到最喜欢的一个即可。

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

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