如何在后台持续运行Python脚本?

2024-09-28 22:37:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个将文件从一个文件夹移动到另一个文件夹的脚本。 但由于原始文件夹是下载文件夹,我需要它总是在后台运行。在

我还有一个标准的批处理文件,如下所示:

@py C:\\Python\Scripts\moveDLs.py %*

我用的是Windows10。我在批处理文件中找到了有关如何使用nohup的Linux和OS信息。 有Windows版本吗?在

如果每次重新启动或开机时都需要执行脚本吗?在

另外,当你设法使其永久化时,你如何终止这个过程?在

非常感谢


Tags: 文件py版本脚本文件夹信息标准os
3条回答

在Windows上,可以使用^{}将python脚本作为后台进程运行:

Python scripts (files with the extension .py) will be executed by python.exe by default. This executable opens a terminal, which stays open even if the program uses a GUI. If you do not want this to happen, use the extension .pyw which will cause the script to be executed by pythonw.exe by default (both executables are located in the top-level of your Python installation directory). This suppresses the terminal window on startup.

例如

C:\ThanosDodd\Python3.6\pythonw.exe C:\\Python\Scripts\moveDLs.py

为了使脚本连续运行,可以使用帮助事件调度的^{}模块:

The sched module defines a class which implements a general purpose event scheduler

^{pr2}$

现在,要在Windows上终止后台进程,只需运行:

taskkill /pid processId /f

其中processId是要终止的进程的ID。在

一种选择是更改脚本,使其能够连续运行而不是重复运行。只需把整个事情打包成一个while循环,然后加上睡眠。在

import time

while True:
   your_script_here
   time.sleep(300)

为了确保这是从计算机启动的,并在发生异常时提供自动重新启动,我建议使用非吸吮服务管理器将其放入Windows服务中(网址:www.nssm.cc). 这有几个步骤(参见文档),但一旦完成,您的脚本将只是另一个windows服务,您可以从标准启动和停止服务.msc实用性。在

我找到了一个有效的解决方案:

import shutil, os, time

while True:
    for filename in os.listdir('folderToMoveFrom'):
        if filename.endswith((desired file extensions)):
            shutil.move( (folderToMoveFrom + filename), folderToMoveTo)
    time.sleep(6)

如果执行上述代码时没有时间。睡觉()函数由于嵌套在另一个“找不到文件”错误中的“找不到文件”错误,程序在新文件进入文件夹后崩溃。 不知道这是怎么回事,但我对我目前的情况很满意。 现在您只需要将脚本添加到任务调度器中,以便在Pythonw下运行,使其作为后台进程运行。或者不用运行脚本,只要记住为pythonw添加适当的指令,就可以运行批处理文件。当然,你只需要启动这个过程一次。在

相关问题 更多 >