Python 自动 运行 程序无需 shell 保持打开状态
Python automatically run program without shell staying open
我在 Python 中使用 ApScheduler 包来安排一个程序每小时 运行。但是,shell window 永远不会关闭,如果我手动关闭它,程序就会终止。当代码不是 运行ning 时,有没有一种方法可以在不看到 window 的情况下安排 python 程序?此外,在 .pyw 中,window 永远不会显示。所以我希望 window 在 运行 期间打开,然后关闭直到下一个 运行。
如果您想随意打开或隐藏 window,您必须使用 GUI 包,例如 TkInter. Then follow this tutorial on how to show or hide a window with TkInter。
如果您 运行 带有 pythonw.exe
的脚本或将脚本另存为 .pyw
,终端 window 将被隐藏。
您只需使用 pythonw.exe
打开作业脚本。
命令提示符中的两行设置所有 python 文件用它打开。
Python Documentation - 3.3.4 Executing scripts
- Launch a command prompt.
- Associate the correct file group with .py scripts:
assoc .py=Python.File
- Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
如果你需要关闭脚本但是 window 是隐藏的,你可以使用 psutil
模块来找到哪个可执行文件正在 运行ning 你的脚本,获取 PID,然后杀了它。
import psutil
scripts = [[" ".join(p.cmdline()), p.pid] for p in psutil.process_iter()
if p.name().lower() in ["python.exe", "pythonw.exe"]]
我在 Python 中使用 ApScheduler 包来安排一个程序每小时 运行。但是,shell window 永远不会关闭,如果我手动关闭它,程序就会终止。当代码不是 运行ning 时,有没有一种方法可以在不看到 window 的情况下安排 python 程序?此外,在 .pyw 中,window 永远不会显示。所以我希望 window 在 运行 期间打开,然后关闭直到下一个 运行。
如果您想随意打开或隐藏 window,您必须使用 GUI 包,例如 TkInter. Then follow this tutorial on how to show or hide a window with TkInter。
如果您 运行 带有 pythonw.exe
的脚本或将脚本另存为 .pyw
,终端 window 将被隐藏。
您只需使用 pythonw.exe
打开作业脚本。
命令提示符中的两行设置所有 python 文件用它打开。 Python Documentation - 3.3.4 Executing scripts
- Launch a command prompt.
- Associate the correct file group with .py scripts:
assoc .py=Python.File
- Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
如果你需要关闭脚本但是 window 是隐藏的,你可以使用 psutil
模块来找到哪个可执行文件正在 运行ning 你的脚本,获取 PID,然后杀了它。
import psutil
scripts = [[" ".join(p.cmdline()), p.pid] for p in psutil.process_iter()
if p.name().lower() in ["python.exe", "pythonw.exe"]]