gpt4 book ai didi

python - 从 Python 启动一个完全独立的进程

转载 作者:IT老高 更新时间:2023-10-28 22:12:32 53 4
gpt4 key购买 nike

我正在尝试从 python 启动一个完全独立的进程。我不能使用像 os.startfile 这样简单的东西,因为我需要传递参数。目前我正在使用 subprocess.popen ,它可以让我完成 90% 的工作。

args = ["some_exe.exe", "some_arg", "another_arg"]
subprocess.Popen(args, creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

popen 与 std* 的分离创建标志和管道一起使用确实会启动一个新进程,该进程在父进程死亡后仍然存在。所以这一切都很好。问题是新的“子”进程仍然持有父进程的虚拟句柄。因此,如果我尝试卸载父 exe(我的 python 脚本通过 pyinstaller 捆绑到一个 exe 中),msiexec 会提示父 exe 仍在使用中。

所以目标是生成一个完全独立的进程来运行“some_exe.exe”,它没有任何句柄返回到原始进程。

注意:这适用于 Windows XP 及更高版本。我正在Win7上开发。

最佳答案

我想我找到了答案。通过将 Popenclose_fds = True 一起使用,我能够启动一个独立且没有父句柄的进程。

查看文档 here并搜索 close_fds

Or, on Windows, if close_fds is true then no handles will be inherited by the child process. Note that on Windows, you cannot set close_fds to true and also redirect the standard handles by setting stdin, stdout or stderr.

请注意,此解决方案仅适用于 Windows。我对任何 *nix 系统一无所知。

关于python - 从 Python 启动一个完全独立的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13592219/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com