Run a child process free of the parent in Python

佐手、 提交于 2020-01-04 15:13:57

问题


I have a program I'm running within another. The parent program freezes up while the child process is running. Is there a way to run the child process in the OS as a parent process itself?


回答1:


You can use subprocess.Popen, assuming you're really trying to launch a program that's completely separate from the parent Python script:

import subprocess
subprocess.Popen(["command", "-a", "arg1", "-b", "arg2"])

This will launch command as a child process of the calling script, without blocking to wait for it to finish. If the parent exits, the child process will continue to run.




回答2:


If you really want to have independent processes, please have a look at the multiprocessing module. If it is enough to have a separate thread running in the same OS process, then use threading. Or are you interested in starting an external program from within a Python script with subprocess?

Unfortunately, the terminology is a bit confusing. For example, in Linux "thread" and "process" are both independent processes with no real difference. In python "process" is a separate OS precess, thread runs in the same OS process.

For more information on these, you might have a look at this question: Multiprocessing vs Threading Python



来源:https://stackoverflow.com/questions/24787106/run-a-child-process-free-of-the-parent-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!