简体   繁体   English

使用Windows 7按计划触发python脚本的最简单方法是什么?

[英]What is the easiest way to trigger a python script on schedule using Windows 7?

When I try to run it using the Task Scheduler, it never works. 当我尝试使用任务计划程序运行它时,它将永远无法工作。 It gives me weird errors like 0x1 and the script is never run. 它给了我0x1之类的怪异错误,并且脚本从未运行。 I have googled this problem and can't really find a sufficient, easy solution. 我已经用谷歌搜索了这个问题,但实际上并没有找到足够简单的解决方案。 (Someone suggested writing a batch script in Windows but I'm not exactly sure how to do that so I'd rather try different avenues first). (有人建议在Windows中编写批处理脚本,但是我不确定该怎么做,因此我宁愿先尝试其他途径)。

On the Task Scheduler GUI in Windows 7, I go to start a program/script and enter the python.exe directory. 在Windows 7中的Task Scheduler GUI上,我启动一个程序/脚本并输入python.exe目录。 The argument that I add to the scheduler GUI is the location of the python script. 我添加到调度程序GUI的参数是python脚本的位置。 I run it with the highest privileges (check box) to no avail (it does not work). 我以最高特权(复选框)运行它,但无济于事(它不起作用)。

If there is an alternative way of running a python script on a schedule, I would be happy to hear about it. 如果有按计划运行python脚本的另一种方法,我很高兴听到它。 I'd rather not use a seemingly ad-hoc method like apscheduler which may require my script to always be running (?). 我宁愿不使用像apscheduler这样的临时方法,该方法可能要求我的脚本始终处于运行状态(?)。 Perhaps there is a way to daemonize this process? 也许有一种方法可以守护这个过程? I did indeed try using celery but it did not work. 我确实确实尝试过使用芹菜,但是没有用。

For example: 例如:

from celery.task import periodic_task
from celery.schedules import crontab

@periodic_task(run_every=timedelta(seconds=30))
def every_30_seconds():
    print("Running periodic task!")

doesn't work either because apparently it is a deprecated decorator. 也不起作用,因为显然它是一个过时的装饰器。 Any help would be appreciated. 任何帮助,将不胜感激。 The print statement is never printed. 打印语句永远不会打印。

Thanks. 谢谢。

I would seriously reconsider Task Scheduler. 我会认真考虑任务计划程序。

I've just set up a quick Python script to run as a scheduled task on my machine, and it works. 我刚刚设置了一个快速的Python脚本,以在计算机上作为计划任务运行,并且可以运行。 (I am however using Windows 8.1 instead of Windows 7, but I can't imagine that would make much difference.) (但是,我使用的是Windows 8.1而不是Windows 7,但我无法想象这会有很大的不同。)

If you can't get a Python script working on its own, you could write a short batch script to start your Python script: something like the following should work: 如果您无法单独使用Python脚本,则可以编写一个简短的批处理脚本来启动Python脚本:类似以下内容的代码应该可以工作:

@echo off
python YourScript.py > output.log 2> errors.log

Feel free to use the full path to the Python executable and/or the various files mentioned in this line. 随意使用Python可执行文件和/或此行中提到的各种文件的完整路径。

Task Scheduler works fine when it does work, but when it can't run a task it can be difficult to find what the problem is, as Task Scheduler will typically show only the exit code. Task Scheduler可以正常工作,但是当它无法运行任务时,很难找到问题所在,因为Task Scheduler通常只显示退出代码。 Writing output/errors to file allows you to see any output or traceback that Python may have generated and help you understand what the problem could be. 将输出/错误写入文件可让您查看Python可能生成的任何输出或回溯,并帮助您了解问题所在。

The following two classes demonstrate how easy it can be to schedule a task in Python and separate the scheduler process from the activity process. 以下两个类演示了用Python计划任务并将计划程序流程与活动流程分开是多么容易。 By dividing the two tasks, you prevent any problems in the activity from propagating into the scheduler (such as memory leaks et cetera). 通过划分两个任务,可以防止活动中的任何问题传播到调度程序中(例如内存泄漏等)。

class Scheduler(sched.scheduler):

    "Scheduler(path, extension) -> Scheduler instance"

    SECOND_1 = 1
    MINUTE_1 = SECOND_1 * 60
    HOUR_1 = MINUTE_1 * 60

    def __init__(self, path, extension):
        "Initialize the scheduler and schedule the first run after a minute."
        super().__init__()
        self.__path = path
        self.__extension = extension
        self.__processed_files = set(self.matched_files)
        self.enter(self.MINUTE_1, 0, self.process_new_files)

    @property
    def matched_files(self):
        "Read-only property of files matching path and extension."
        return glob.iglob('{}\\*.{}'.format(self.__path, self.__extension))

    @property
    def unprocessed_files(self):
        "Read-only property of files that have not been processed."
        return set(self.matched_files) - self.__processed_files

    def process_new_files(self):
        "Schedule to run later and process any unprocessed files."
        self.enter(self.HOUR_1, 0, self.process_new_files)
        print('Checking for unprocessed files @', time.strftime('%c'))
        for file in self.unprocessed_files:
            print('Processing:', repr(file), '...', end='')
            processor = Processor(file)
            processor.start()
            processor.join()
            self.__processed_files.add(file)
            print(' DONE')
        print()

################################################################################

class Processor(multiprocessing.Process):

    "Processor(file) -> Processor instance"

    def __init__(self, file):
        "Initialize processor with the file that needs to be processed."
        super().__init__()
        self.__file = file

    def run(self):
        "In a new process, run the original program while logging errors."
        log_errors(process_files, (self.__file, 'Items.txt'))

i'd revisit the task scheduler, assuming always running while PC is on, try the following: 我会重新访问任务计划程序,假设PC始终在运行时运行,请尝试以下操作:

1) open task scheduler 1)打开任务计划程序

2) in the menubar click "Action" and then "Create Task" 2)在菜单栏中单击“操作”,然后单击“创建任务”

3) under the "General" tab, give it a name and description, and configure your security options 3)在“常规”标签下,为其提供名称和描述,并配置您的安全选项

4) under the trigger tab, click "New..." 4)在触发标签下,点击“新建...”

5) in the "Begin the task" dropbox select "At Startup" 5)在“开始任务”下拉框中,选择“启动时”

6) check the "repeat task every" box and then set the repeat interval 6)选中“每隔重复任务”框,然后设置重复间隔

7) click "Ok" then open "Actions" Tab 7)点击“确定”,然后打开“操作”标签

8) add the path to python in the "programs/script" box 8)在“程序/脚本”框中添加python的路径

9a) either add the complete path to your script in the "Add arguments" box or: 9a)在“添加参数”框中添加完整的脚本路径,或:

9b) add the directory of your script into the "start in" box and then just the script name to the arguments box 9b)将脚本目录添加到“开始于”框中,然后仅将脚本名称添加到参数框中

10) click ok 10)点击确定

this should work no problems HOWEVER if there are spaces in any of your path names, you will need to enclose them in quotes, else they will be interpreted as separate arguments and python will be unable to do anything with it. 这应该没有问题,但是,如果任何路径名中都有空格,则需要将其用引号引起来,否则它们将被解释为单独的参数,而python将无法对其进行任何处理。

James 詹姆士

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM