qew*_*jhb 3 python windows subprocess background-process python-3.x
我的问题类似于How to run Python's subprocess and left it in back,但是那里列出的答案都不适合我。
我尝试运行一个程序,例如 Slack 或 Discord(或问题更新中列出的其他程序)。即使我的脚本完成,我也希望程序能够运行。
我需要这个才能在 Windows 上工作。
注意:仅当 Slack / Discord 从 Python 脚本启动时才会出现此问题,如果之前运行过,则不会关闭。
示例代码:(如您所见,我尝试了多种方法):
import os, subprocess
from time import sleep
from subprocess import Popen, PIPE, STDOUT
# discord_path=r"C:\Program Files\Discord\Discord.exe"
# discord_path2=r"C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Discord Inc\Discord.lnk"
# os.startfile(discord_path2)
# subprocess.run([r"C:\Users\user\AppData\Local\Discord\Update.exe", "--processStart", "Discord.exe"],shell=True)
# subprocess.Popen([r"C:\Users\user\AppData\Local\Discord\Update.exe", "--processStart", "Discord.exe"],shell=True)
# subprocess.call([r"C:\Users\user\AppData\Local\Discord\Update.exe", "--processStart", "Discord.exe"])
# subprocess.Popen([r"C:\Users\user\AppData\Local\Discord\Update.exe", "--processStart", "Discord.exe"], stdin=None, stdout=None, stderr=None, close_fds=True)
# slack_path2=r"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Slack Technologies Inc\Slack.lnk"
# os.startfile(slack_path2)
# stdin=None, stdout=None, stderr=None,
# subprocess.Popen([r"C:\Program Files\Slack\slack.exe", "--startup"], close_fds=True)
proc = Popen([r"C:\Program Files\Slack\slack.exe", "--startup"], stdout=PIPE, stderr=STDOUT)
sleep(5)
# now program (Slack / Discord) is exited and I can't prevent it
Run Code Online (Sandbox Code Playgroud)
更新:
我还测试了notepad.exe、calc.exe和winver。
notepad.exe其winver行为与 Slack 和 Discord 相同。然而,calc.exe脚本完成后保持打开状态(因此该程序表现异常)。
代码:
subprocess.Popen(['notepad.exe'])
subprocess.Popen(['calc.exe'])
subprocess.Popen(['winver'])
Run Code Online (Sandbox Code Playgroud)
更新 2:
我需要以这种方式运行一些程序(包括 Slack 和 Discord),所以使用os.execl()不会完成这项工作,因为它会立即退出 python 脚本。
更新 3: 当我添加一条评论时,结果发现我是从 vscode 中运行 python,并且 vscode 在主 Python 脚本完成后以某种方式关闭进程。当我从 Powershell 运行 Python 脚本时,下面的大多数答案都会按预期工作。
You should use os.spawn*() function to create new process
Here's your example:
We run the program at the path with the nonblocking flag os.P_NOWAIT
The last two arguments are given to the process. (yeah, if you're not familiar, the first argument should be the path of the program, by which it's called, and then your arguments, for more info google 'argv')
import os
path = r"C:\Program Files\Slack\slack.exe"
os.spawnl(os.P_NOWAIT, # flag
path, # programm
path, "--startup") # arguments
print("Bye! Now it's your responsibility to close new process :0")
Run Code Online (Sandbox Code Playgroud)