如何在Windows后台在后台不断运行Python脚本? [英] How to constantly run Python script in the background on Windows?

查看:1375
本文介绍了如何在Windows后台在后台不断运行Python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个脚本,用于将文件从一个文件夹移动到另一个文件夹. 但是由于原始文件夹是下载"文件夹,所以我需要它始终在后台运行.

I have created a script that moves files from one folder to another. But since the original folder is the Downloads folder I need it to always run in the background.

我还有一个标准的批处理文件,看起来像这样:

I also have a standard Batch file that looks something like this:

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

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

I'm using Windows 10. I have found info for Linux and OS on how to use nohup in the batch file. Is there a Windows version?

如果有的话,每次重启或打开PC时都需要执行脚本吗?

If there is do you need to execute the script every time you restart or switch the PC on?

此外,当您设法使其永久化时,如何终止该过程?

Also, how do you terminate the process when you do manage to make it permanent?

非常感谢

推荐答案

在Windows上,您可以使用 pythonw.exe 以便将python脚本作为后台进程运行:

On Windows, you can use pythonw.exe in order to run a python script as a background process:

Python脚本(扩展名为.py的文件)将由 python.exe默认情况下.该可执行文件将打开一个终端,该终端将停留在 即使该程序使用GUI也可以打开.如果您不希望这样 如果发生这种情况,请使用扩展名.pyw,这将导致脚本被 默认情况下由pythonw.exe执行(两个可执行文件都位于 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

为了使脚本连续运行,可以使用 sched 可帮助安排事件的模块:

In order to make your script run continuously, you can use the sched module that helps with event scheduling:

sched模块定义了一个实现通用目的的类 事件调度程序

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

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()

现在,要杀死Windows上的后台进程,您只需要运行:

Now in order to kill a background process on Windows, you simply need to run:

taskkill /pid processId /f

processId是您要终止的进程的ID.

Where processId is the ID of the process you want to kill.

这篇关于如何在Windows后台在后台不断运行Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆