Scheduling a .py file on Task Scheduler in Windows 10
Asked Answered
S

13

54

I already tried to convert my .py file into .exe file. Unfortunately, the .exe file gives problems; I believe this is because my code is fairly complicated. So, I am trying to schedule directly my .py file with Task Scheduler but every time I do it and then run it to see if works, a window pops up and asks me how I would like to open the program?-.-

Does any of you know how I can successfully schedule my .py file with Task Scheduler?

Windows 10 Python 3.5.2

Seymourseys answered 23/6, 2017 at 17:45 Comment(2)
Schedule Python exe with the script as argument?Treviso
@DaveS Can you please be more specific, because I have tried it but it did not work. So I don't know if I did something wrong in the process or it just doesn't work. ThanksSeymourseys
B
59

Creating the exe should be the best method. But if you want to run it with the task scheduler you can do it in this way:

  1. Launch Window’s Task Scheduler
  2. Look for the The Actions pane(on the right) it has the Create Basic Task action. Click on it.
  3. This will open a wizard where you will define the name of your task, the trigger (when it runs), and the action (what program to run). Action tab is where you specify the name of your Python script to run as well as any arguments to the script.

To ensure that your Python script will run regardless of the login account that the schedule task uses, and to avoid any confusion about which version of Python is used in mixed environments (64bit or 32bit), it is recommended that you run the Python executable with the name of your Python file as an argument to the executable.

Suppose the script you want to run is E:\My script.py. Instead of running the script directly, instruct the task scheduler to run python.exe with the script as an argument. For example:

C:\Python27\ArcGIS10.2\python.exe "E:\My script.py"

The location of python.exe depends on your install. If you don’t know where it is, you can discover its location; copy and paste the following code into a new Python script then execute the script. The script will print the location of python.exe as well as other information about your Python environment.

import sys
import platform
import imp

print("Python EXE     : " + sys.executable)
print("Architecture   : " + platform.architecture()[0])
print("Path to arcpy  : " + imp.find_module("arcpy")[1])

raw_input("\n\nPress ENTER to quit")

After determining the location of python.exe, this is what is entered in the Action panel of the task scheduler: enter image description here

If there are additional arguments (parameters) to your script, provide them after the path to your script. Hope this helps.

Biometrics answered 23/6, 2017 at 18:2 Comment(15)
Unfortunately it does not work. It runs, it opens the Command Prompt but it closes after one second without executing my code.Seymourseys
You sure your code is working correct. It works for meBiometrics
All I am doing in this code is to prompt a user to enter a word. k = input("enter word: ") print(k)Seymourseys
Ok, does it go out in a flash?. does it show any error? Make sure that the highest privileges is checked, and the path to the python script is in the "Start In" box.Biometrics
It goes out in a flash and it shows an error: ImportError: no module named "arcpy"Seymourseys
Is your script located in a different location other than the python folder. try putting it in that folder.Biometrics
Oh Wait, so the path of the python script should be in the "Start in" Box and not in the "Add argumetns" box? ill correct itSeymourseys
See if it is working or not. Refer this image for help. i.imgur.com/AzeHrDw.jpgBiometrics
Nothing, I don't know what's wrong with it but it's not working :(Seymourseys
if it's running then it's ok, now your task is just to find out why it cannot import arcpy.Biometrics
Sorry, my comment was wrong. The arcpy module was in the script that allowed my to see where python.exe was. I did not mean to schedule that scrypt (but even in that case something was off because it wouldnt load the arcpy module). I also simply tried a script that would just print("PleaseWork"), and nothing, thins thing hates meSeymourseys
Ok can we just try to run it through a batch file?. because running a batch file through the scheduler would be much easier.Biometrics
Yes Please, but I would need instrucitons on how to do itSeymourseys
for batch file you can refer this. #44480987. Glad, if I was of any helpBiometrics
I didn't try this too much and honestly I don't really think it should matter, but I only got this to work after I added the path to the python script folder ("E:\") in "Start in" and only had the script ("My script.py") in "Add arguments". However, in my opinion, this looks better anyway.Acclivity
O
17

Dragon's answer works fine as long as your script not takes much time to finish.

I used a little different approach in the Windows task scheduler:

In Program/script textbox you set the path to Python executable (in my case is inside the virtualenv folder).

Add arguments = Just the name of your Python script.

Start in = The full path of your Python script (without the name.py).

enter image description here

This way the script runs, the console stays open and waits until the end.

Outdare answered 27/11, 2019 at 22:48 Comment(1)
Brilliant. This was the only way it would work for me.Cultivated
I
16

You should set in the Action tab:

  • in programs, the path to your python.exe: for instance "C:\Users\Me\AppData\Local\Programs\Python\Python36\python.exe"
  • in arguments, the full path to your file including the extension: for instance "C:\Users\Me\Desktop\mypythonsrcipt.py"
  • for start in: leave empty

If this doesn't work, try :

  • in programs, the path to your python.exe: for instance "C:\Users\Me\AppData\Local\Programs\Python\Python36\python.exe"
  • in arguments, your filename with the extension: for instance "mypythonsrcipt.py"
  • in start in, the folder of you script : for instance "C:\Users\Me\Desktop\"

Also each time I modify a task, the user account in the General tab is switched to Medium Mandatory Level. So I have to reopen the taks and set the user account back to my username: (cf. this question)

enter image description here

If you still can't run your script, go in Event Log, Applications and Service Log/Microsoft/Windows/TaskScheduler/Operational (right click it to enable it) and look for the errors.

Inglis answered 2/7, 2017 at 17:46 Comment(0)
M
12

I almost lost my hair over this. I always got 0x1 as the result of doing what is described above. A long experienced Windows admin told me this:

Create a batch file:

SET logfile="C:\Reports\batch.log"
@echo off
@echo Starting Script at %date% %time% >> %logfile%
"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe" "C:\Users\sys_www\source\repos\hardware\ReportAssembler.py"
@echo finished at %date% %time% >> %logfile%

Then provide the batch file in the action part of the task config. One thing to also take care of that all the files written during the runtime of the python program can actually be accessed by the user executing the script.

I tried using the script as a parameter and the python exe in programm/script. First I go the error "Windows Scheduled Tasks not running". Then after some configuring around I got the error 0x1, which told me absolutely nothing.

Mckenzie answered 24/9, 2018 at 13:0 Comment(1)
Error (0x1) can be caused by paths or insufficient privileges. you could try check/uncheck Run with highest privileges (both ways). Pathwise, you'd just need the .bat file in the same directory as your Report Assember.py script so your simplified .bat will look like: @echo off "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\python.exe" "ReportAssembler.py". That's it, save yourself some hair :)Mannerless
H
1

The script you execute would be the exe found in your python directory ex) C:\Python27\python.exe

The "argument" would be the path to your script ex) C:\Path\To\Script.py

So think of it like this: you aren't executing your script technically as a scheduled task. You are executing the root python exe for your computer with your script being fed as a parameter.

Hyperbolize answered 23/6, 2017 at 19:6 Comment(9)
Yes I get this, but for some unknow reason it is not working. The Command Prompts opens and after a second closes without running my scriptSeymourseys
In the task scheduler program, what error code does it list (if at all) for "Latest Run Result"Hyperbolize
Does it say 0x0 ?Hyperbolize
I might be looking in the wrong window but it displays nothingSeymourseys
When you open task scheduler, there is a table of contents on the left side. Highlight the directory where your task is. Once you do that, you should see your task in the list of tasks in the center top of the window of the task scheduler. The sixth column in this list is the "Last Run Result" column. It will have a description and a code (or just a code).Hyperbolize
Got it. I get 0x1Seymourseys
Ok, under the "general" tab, click "Run with highest privileges". Also, 0x1 can be an error in your code as well.Hyperbolize
I had already checked that one and my code is as simple as print("PleaseWork")Seymourseys
Yes it does, without problemsSeymourseys
W
1

For some reason, the windows task scheduler starts the python.exe in an environment, where they fail at import-module statements. I had to use a workaround using the CMD.exe and pass the command to run the python script in the given folder.

Use the program

CMD

then the options tab:

/c python main.py

and fill in the source location in the tab Start in:

C:\Users\...

Not sure what's the reason for that. The previously described solutions all did not work for me.

Weimaraner answered 16/7, 2019 at 18:51 Comment(0)
G
0

This worked for me, you could try with the Action pane: The Action pane

Please note that the path of py file in the double quotes, add arguments: $(Arg0)

Check "Run with highest privileges" in the General tab, and it'd better to choose "Run a new instance in parallel" in drop down menu in Settings tab.

After all, you could set the schedule for task in Triggers tab to check the effect of changes (remember choose "Run whether user is logged on or not" in the General tab).

Glassful answered 11/4, 2019 at 5:16 Comment(0)
B
0

This absolutely worked for me . I am using windows 10 professional edition and it has taken me almost 6 months to get this solution.Thanks to the suggestion made above.

I followed this suggestion and it worked right away and smoothly. All I did was to instruct the scheduler to run python.exe with my script as an argument just as explained by this fellow below

This what I did Suppose the script you want to run is E:\My script.py. Instead of running the script directly, instruct the task scheduler to run python.exe with the script as an argument. For example:

C:\Python27\ArcGIS10.2\python.exe

"E:\My script.py"

The location of python.exe depends on your install. If you don’t know where it is, you can discover its location; copy and paste the following code into a new Python script then execute the script. The script will print the location of python.exe as well as other information about your Python environment.

Blameworthy answered 16/9, 2019 at 16:53 Comment(1)
Hi @Emmy, welcome to Stack Overflow and thank you for taking the time to participate in the discussion. That said, I'd like to point out that this is not a regular forum but a Q&A site, therefore a response should only be written if you can provide a new solution for the outlined problem. If an existing solution works for you, you should vote it up and/or comment on it if you have something to add. I invite you to read stackoverflow.com/help/how-to-answer and to keep being part of the community.Loveland
K
0

The scheduler with a batch file worked for me, but in addition to the full path of a particular python.exe as described above, you may also need/want to start a conda environment for all the other python packages. This line can be added to the batch file:

call C:\ProgramData\Anaconda3\condabin\conda.bat activate myenv

ie note the syntax for conda activate from within a batch file is a little different. It was also necessary first to run

conda init cmd.exe

to set up windows command terminal for the use of conda.

Also if setting up to run on a remote machine note there is a command line interface for the scheduler, so you don't even need an RDP session to the remote machine, but can set it all up in an ssh session alone:

schtasks /create /SC ONCE /TN <taskname> /TR C:\full\pathto\scheduledtask.bat /ST <hh:mm>
Knighthead answered 15/3, 2021 at 22:28 Comment(0)
A
0

I was running into the same issue, however none of the above fixes worked.

What ended up causing the failure was due to the fact I was attempting to access a mapped network drive - in my case, T:\

For example, when attempting to run T:\Anancond\envs\my_env\python.exe as the program, I received error 2147942402. Changing the program to \\my\network\location\Anancond\envs\my_env\python.exe allowed me to run with no error.

Acquisition answered 20/7, 2023 at 21:37 Comment(0)
G
0

Recommended solution with python.exe was not working for my python wheel file .whl.

At the end the exact command I was using in command line to run my python wheel worked also in TaskManager, just needed to be splitted to proper fields.

Command line command:

py -m my_wheel.runner ./testConf.yaml

Task scheduler Action definition:

Program: py

Args: -m my_wheel.runner "./testConf.yaml"

Execution path: E:\programs\myPythonWheel\ (This is path from where I was executing it while using command line)

enter image description here

Gabionade answered 11/3 at 21:24 Comment(0)
C
-1

Another option is using Powershell to run your Python script, and point the Task Scheduler action to the Powershell script.

  1. Add a Powershell script, run_script.ps1, in the same directory as my Python script. Contents of run_script.ps1:

    & py "$PSScriptRoot\script.py"

$PSScriptRoot is an automatic variable set to the current file's/module's directory

  1. Set up a Scheduled Task with an Action like this:
    Program/script: pwsh.exe
    Add arguments: -ExecutionPolicy Bypass "C:\my_script_path\run_script.ps1"
    Start in: C:\my_script_path
Cockhorse answered 15/8, 2023 at 16:46 Comment(0)
L
-2

My Python file didn't want to run from the scheduler and execute all the listed above ways. I assume it's related to an infinite loop and the scheduler library, but I could be wrong.

I made a not-so-good decision - to convert the py file to exe (do at your own risk, it's wrong because there are no Python compilers to Exe). However, after converting to exe, I was able to simply add the file to the scheduler and run it - everything works.

Langobard answered 4/3 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.