Scheduling a Python Script via Windows Task Scheduler

爷,独闯天下 提交于 2019-12-11 03:48:53

问题


Observe the following Python script, "Script.py":

import subprocess
src_directory = 'Z:\z_7z\Some_Directory'
zip_file_name = 'Test.7z'
cmd = ['7z', 'a', zip_file_name, src_directory, '-mx9']
subprocess.Popen(cmd, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)

My intent is to schedule a Python script using Windows Task Scheduler. I have successfully done this using other Python scripts before. However, I am unable to execute the script shown above via scheduling. I am unsure as to whether this is a Windows Task Scheduler problem or a Python problem, but here is what I know:

"Script.py", as shown above, is a script for running a 7zip compression on a "Some_Directory" directory. The script itself and the 7z.exe application which it is invoking are both stored in the "Y:\z_7z" directory.

The script seems to be working fine when executed manually. I can double-click on the script and it will execute properly. Also, I can execute the script from the command line via the following command:

Y:\z_7z\Script.py

However, I cannot execute the script manually by navigating to the "C:\Python27" directory and attempting the following:

python Y:\z_7z\Script.py

This yields the following error:

Line 5 in module subprocess.Popen(cmd, stderr = subprocess.STDOUT, ...)
WindowsError: [Error 2] The system cannot find the file specified

Provided all of that information, the real problem I am having is that Windows Task Scheduler cannot execute this script (Last Run Result = 0x1). I have tried various Windows Task Scheduler configurations, including the one which seems to be ideal which goes as follows:

  • Program/script: "C:\Python27\python.exe"
  • Add arguments (optional): "Y:\z_7z\Script.py"
  • Run whether user is logged on or not

Again, I have scheduled other Python scripts before which have run successfully. This Windows Task Scheduler task seems to be configured properly. I browsed through some of the more advanced settings and did not find anything suspicious with this particular task.


回答1:


  1. Don't just launch 7z. Provide the full path to the executable.

    cmd = [r'C:\Program Files\7zip\7z.exe', 'a', zip_file_name, src_directory, '-mx9'] Would work, considering that C:\Program Files\7zip\7z.exe is the executable path.

  2. Try not running the python process with the script as an argument. Run the python script itself.

  3. Your zip_file_name is relative. I'm not sure the argument is a filename. It may be a path. In that case, the .7z file may be created on C:\Windows\System32. To fix it, set zip_file_name to be a full path.



来源:https://stackoverflow.com/questions/11073205/scheduling-a-python-script-via-windows-task-scheduler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!