Tha*_*odd 17 python background-process nohup
我创建了一个将文件从一个文件夹移动到另一个文件夹的脚本。但由于原始文件夹是下载文件夹,我需要它始终在后台运行。
我还有一个标准的批处理文件,看起来像这样:
@py C:\\Python\Scripts\moveDLs.py %*
Run Code Online (Sandbox Code Playgroud)
我正在使用Windows 10。我找到了有关如何nohup在批处理文件中使用的 Linux 和操作系统信息。有 Windows 版本吗?
如果有需要每次重新启动或打开PC时都执行脚本吗?
另外,当您设法使其永久化时,您如何终止该过程?
非常感谢
Gio*_*ous 16
在 Windows 上,您可以使用pythonw.exe将 python 脚本作为后台进程运行:
默认情况下
.py将执行Python 脚本(带有扩展名的文件)python.exe。此可执行文件会打开一个终端,即使程序使用 GUI,该终端也会保持打开状态。如果您不希望发生这种情况,请使用默认情况下.pyw会导致脚本执行的扩展名pythonw.exe(两个可执行文件都位于 Python 安装目录的顶层)。这会在启动时抑制终端窗口。
例如,
C:\ThanosDodd\Python3.6\pythonw.exe C:\\Python\Scripts\moveDLs.py
Run Code Online (Sandbox Code Playgroud)
为了让你的脚本持续运行,你可以使用sched事件调度:
sched 模块定义了一个实现通用事件调度器的类
import sched
import time
event_schedule = sched.scheduler(time.time, time.sleep)
def do_something():
print("Hello, World!")
event_schedule.enter(30, 1, do_something, (sc,))
event_schedule.enter(30, 1, do_something, (s,))
event_schedule.run()
Run Code Online (Sandbox Code Playgroud)
现在为了杀死 Windows 上的后台进程,您只需要运行:
taskkill /pid processId /f
Run Code Online (Sandbox Code Playgroud)
processId要杀死的进程的 ID在哪里。
一种选择是更改脚本,使其连续运行而不是重复运行。只需将整个事情包装在一个 while 循环中并添加一个睡眠即可。
import time
while True:
your_script_here
time.sleep(300)
Run Code Online (Sandbox Code Playgroud)
为了确保它随计算机启动并在发生异常时提供自动重新启动,我建议使用 Non-Sucking Service Manager (www.nssm.cc) 将其设置为 Windows 服务。有几个步骤(请参阅文档),但一旦完成,您的脚本将只是另一个 Windows 服务,您可以从标准 services.msc 实用程序启动和停止它。