Running a python script through Windows Scheduler not working - python

I am trying to automate a python script through the Windows Task Scheduler but its not working. At the end of my python script. two CSV files should be created but they arent.
I tried the following:
1. Copied the address of my python.exe to Program/Script.
C:\Program Files\Python35\python.exe
In the Add arguments, i put the name of my file
Historical Aggregation.py
In the Start in (optional), i put the path of my python script
C:\Users\myname\PycharmProjects\Project1
Am I missing something

To simplify, we can create a really short .bat file, that will only receive the necessary command to run your python script.
To do so, try this:
Create a executePy.bat file in the same folder than your Python file (C:\Users\myname\PycharmProjects\Project1), with content:
#echo off
"C:\Program Files\Python35\python.exe" "Historical Aggregation.py"
Then, on your task scheduler, simply schedule a test with Program/Script:
"C:\Users\myname\PycharmProjects\Project1\executePy.bat"
Leave Add Arguments and Start In in blank. Now, your task should be ready to run.

I had a very similar issue, and solved it in a different way. Here my step by step guide:
Transform the python script to an .exe, using in the DOS cmd prompt the command:
pyinstaller -- onefile [name of the file.py]
Place the CSV file that you want to update in the same folder as the .exe file created
Create a basic task on Windows Scheduler, with the following properties:
General - select
Run whether user is logged on or not
add the PC password. For my PC, use the user name DESKTOP-M40FS79\dario and the PC password
Run with highest privileges
Triggers – select
Daily
Repeat task every 30 minutes
Stop task if it runs longer than 15 minutes
Actions
Under Program/ Script insert the path to your .exe file, for instance, C:\Pythondata\dist\test.exe
Under Start in (optional) insert the path to the directory where the CSV and .exe files are, for instance C:\Pythondata\dist\
Conditions - select
Start the task only if the computer is on AC power, and make sure you have connected the power
Wake the computer to run this task
Settings – leave the default options
Save the task by inserting the password
Leave the task status on “Ready”
Good luck!

Another approach would be to set fields as:
Program/Script - your python path (with quotation marks):
"C:\Program Files\Python35\python.exe"
Add arguments - full file name of the script, including it's path (with quotation marks):
"C:\Users\myname\PycharmProjects\Project1\Historical Aggregation.py"

Related

Python script can't find file when using Windows Scheduler

I have a batch file to execute Python and run a Python script that works fine when run manually. But when run using Windows Task Scheduler, the Python Script gives me a traceback because it can't find a .TXT file that's in the same file as the Python script.
There are many flavors of the "batch file works manually but not with Task Scheduler" problem. I think my problem may be related to the fact that my Python script is in a virtual environment. It may also be related to Windows user accounts and permissions. Past posts about Task Scheduler have been resolved with changing settings related to user accounts but so far that hasn't worked for me.
More details on Windows Task Scheduler settings:
Here are the settings I've chosen for the task:
My task gets closest to working when I use the "run only when user is logged on option. If I choose "run whether user is logged on or not" the task opens a Command Prompt but doesn't appear to execute anything.
More details about batch file
My batch file looks like this:
"C:\Users\MyPathtovirtualenvironment\virtualenv\Scripts\python.exe" "C:\Users\fried\Desktop\calendaralert\court_calendar_alert1.3_automatic.py"
pause
When run manually, it does what it's supposed to: it executes Python from within the virtual environment, then loads the Python script, which runs correctly except when it's run from Windows Task Scheduler.
More details on Python script
The Python script works fine when run by itself in the command prompt and as a batch file, so I don't think there's anything directly wrong with it. Here's the part of the script that causes the traceback.
with open('replacements.txt') as f:
replacements = dict(x.rstrip().split("!") for x in f)
The replacements.txt file is in the same folder as my Python program. I also tried putting copies of the file within the Virtual Environment folder and the /scripts subfolder without success.
Just came across this problem, while running a python script on a windows ec2 instance. The problem got solved by adding this at the top:
import os
path = "your-directory-path"
os.chdir(path)

Task Scheduler returns 0xFFFFFFFF in Windows 7

I created a Python script that collects data from a website and generates an Excel file based on a table in that website. I used pyinstaller with -w -F parameters to generate a .exe file.
I ran this file a few times and it worked perfect so I decided to use Task Scheduler to run it every hour. Two days after the task worked every hour, while I was using the computer the Task Scheduler returned this error when it tried to run the .exe: 0xFFFFFFFF and a pop-up saying: Failed to "something"
Given the fact that I needed data every hour, I ran the file manually and again... it worked!
Is there any way I can fix this? How can I make sure that it won't fail again when I leave my computer online for 1 week but I'm not there to manually start it in case it fails...
Here are the settings for the Task Scheduler:
Actions:
Program/script: C:\path1\path2\path3\Script_G1.exe
/ Start in (optional): C:\path1\path2\path3\
Settings:
Allow task to be run on demand
We had a similar problem where we'd get a 0xFFFFFFFF error when running our custom .exe from Task Scheduler, but it would work fine outside of Task Scheduler.
The workaround was to create a .bat file to run the .exe and make the scheduled task call the .bat file. Not a solution, obviously, but works in a pinch.
We had a similar problem. The program accessed shared disk F:\SomeFolder\File.log and copied a file from it to the local folder. I had to change the shared disk path name in the program to use full server path.
From
F:\SomeFolder\File.log
to
\\serverName\\docs\\SomeFolder\File.log
and then it worked.
In the "Action" check the "Start in (optional)" field. It makes a difference in these situations.

Unable to Correctly Run Python Scripts Through Scheduler

So I've researched and tested multiple methods to get this to work, but both our IT guy and myself are unsure how to proceed. Ultimately I need to run three python scripts on a server which look at a set of Excel files and scans them for errors. If there are errors, it will email the appropriate people to fix them. The scripts themselves work fine when run through the CMD prompt, either individually or in a batch file. These scripts work perfectly when run manually from the command prompt.
However, when I try to schedule one of the scripts or the batch file, they do not run in their entirety. I have a print statement early on in the scripts and that runs fine in the Python.exe, but then the script abruptly quits. This makes me think that Python runs fine, but the contents of the script aren't running correctly through the scheduler.
To simplify troubleshooting I created two test scripts, test.py and test2.py, and placed them in a simple directory of the server, C:\Store. All this first script does is print something to the console, and write something to a file and save it to the root directory, after which it will wait for user input. The second script is simpler and just prints the architecture of Python and it's build path. Both scripts work fine when run from the command prompt manually.
**test.py** Does NOT Work as scheduled task
import io
print('JUST WORRRRRKKK!')
with open("//kaicmapp/Store/foobar.txt", "w") as file:
file.write("Hello!")
file.close()
raw_input("press any button")
**test2.py** Works as scheduled task
import sys
import platform
print("Python EXE : " + sys.executable)
print("Architecture : " + platform.architecture()[0])
raw_input("\n\nPress ENTER to quit")
What I am using for these test scripts:
Python 2.7 32 bit
Windows Server 2012
Windows User Profile with Admin Rights
Python 2.7 exe added as environment variable. Renamed to python2.exe in installation directory, as I also have Python 3 installed on the serverand want to be able to run them exclusively
Things I've tried:
Running Task Scheduler as Admin
Run with/without highest privileges
Run only when current user is logged in
Run regardless of current user logged in, password entered correctly
Run the scripts in a batch file
The solution listed here, results in same outcome in both scripts
Things I've noticed:
Using python2 "C:\Store\test2.py" in the scheduler will run the script successfully, with the prompt waiting for user input. Run result from the scheduler says The operation completed successfully. (0x0)
Using the same task as above, but running test.py instead, will not result any output from the Python shell, it simply pops up and disappears. Run result from scheduler says Incorrect function. (0x80070001)
Any ideas on how to proceed? I am not very familiar with server administrative tasks, so I feel pretty lost here.
This is a Microsoft scheduler issue.
https://social.technet.microsoft.com/Forums/windows/en-US/c8ad90e1-8435-4e13-9af9-098e72a1926d/error-code-incorrect-function-0x80070001-when-running-a-scheduled-task?forum=winserver8gen
Please check if this solution works for you.

Windows scheduler keeps asking if I want to keep using Python.exe to open .py files

I have a script that scheduler is to run daily. Each time, it asks if I want to keep using Python.exe, even though it's already the default program for opening such files.
Some advice elsewhere suggested deleting the UserChoice registry entry for .py files, which did nothing to resolve.
How can I get my system to stop prompting, so it will run the script without user input?
Do you have the scheduler pointed directly at the .py file? If so, I'd recommend instead to tell the scheduler to run python.exe and pass the .py file as an argument.
For example, if the script you want to run is C:\Files\script.py put this into the scheduler:
C:\Python27\ArcGIS10.2\python.exe "C:\Files\script.py"

Problems running python script by windows task scheduler that does pscp

Not sure if anyone has run into this, but I'll take suggestions for troubleshooting and/or alternative methods.
I have a Windows 2008 server on which I am running several scheduled tasks. One of those tasks is a python script that uses pscp to log into a linux box, checks for new files and if there is anything new, copies them down to a local directory on the C: drive. I've put some logging into the script at key points as well and I'm using logging.basicConfig(level=DEBUG).
I built the command using a variable, command = 'pscp -pw xxxx name#ip:/ c:\local_dir' and then I use subprocess.call(command) to execute the command.
Now here's the weird part. If I run the script manually from the command line, it works fine. New files are downloaded and processed. However, if the Task Scheduler runs the script, no new files are downloaded. The script is running under the same user, but yet yields different results.
According to the log files created by the script and on the linux box, the script successfully logs into the linux box. However, no files are downloaded despite there being new files. Again, when I run it via the command line, files are downloaded.
Any ideas? suggestions, alternative methods?
Thanks.
You can use the windows Task Scheduler, but make sure the "optional" field "Start In" is filled in.
In the Task Scheduler app, add an action that specifies your python file to run "doSomeWork" and fill in the Start in (optional) input with the directory that contains the file.. So for example if you have a python file in:
C:\pythonProject\doSomeWork.py
You would enter:
Program/Script: doSomeWork.py
Start in (optional): C:\pythonProject
I had the same issue when trying to open an MS Access database on a Linux VM. Running the script at the Windows 7 command prompt worked but running it in Task Scheduler didn't. With Task Scheduler it would find the database and verify it existed but wouldn't return the tables within it.
The solution was to have Task Scheduler run cmd as the Program/Script with the arguments /c python C:\path\to\script.py (under Add arguments (optional)).
I can't tell you why this works but it solved my problem.
I'm having a similar issue. In testing I found that any type of call with subprocess stops the python script when run in task scheduler but works fine when run on the command line.
import subprocess
print('Start')
test = subprocess.check_output(["dir"], shell=True)
print('First call finished')
When run on command line this outputs:
Start
First call finished
When run from task scheduler the output is:
Start
In order to get the output from task scheduler I run the python script from a batch file as follows:
python test.py >> log.txt
I run the script through the batch file both on command line and through task scheduler.
Brad's answer is right. Subprocess needs the shell context to work and the task manager can launch python without that. Another way to do it is to make a batch file that is launched by the task scheduler that calls python c:\path\to\script.py etc. The only difference to this is that if you run into a script that has a call to os.getcwd() you will always get the root where the script is but you get something else when you make the call to cmd from task scheduler.
Last edit - start
After experiments... If you put there full path to python program it works without highest privileges (as admin). Meaning task settings like this:
program: "C:\Program Files\Python37\python.exe"
arguments: "D:\folder\folder\python script.py"
I have no idea why, but it works even if script uses subprocess and multiple threads.
Last edit - end
What I did is I changed task settings: checked Run with highest privileges. And task started to work perfectly while running python [script path].
But keep in mind, that title contains "Administrator: " at the begining... always...
P.S. Thanks guys for pointing out that subprocess is a problem. It made me think of task settings.
I had similar problem when one script is running from Windows Task Scheduler, and another one doesn't.
Running cmd with python [script path] didn't work for me on Windows 8.1 Embedded x64. Not sure why. Probably because of necessity to have spaces in path and issue with quotes.
Hope my answer helps someone. ;)
Create a batch file add your python script in your batch file and then schedule that batch file .it will work .
Example : suppose your python script is in folder c:\abhishek\script\merun.py
first you have to go to directory by cd command .so your batch file would be like :
cd c:\abhishek\script
python merun.py
it work for me .
Just leaving this for posterity: A similar issue I faced was resolved by using the UNC (\10.x.xx.xx\Folder\xxx)path everywhere in my .bat and .py scripts instead of the letter assigned to the drive (\K:\Folder\xxx).
I had this issue before. I was able to run the task manually in Windows Task Scheduler, but not automatically. I remembered that there was a change in the time made by another user, maybe this change made the task scheduler to error out. I am not sure. Therefore, I created another task with a different name, for the same script, and the script worked automatically. Try to create a test task running the same script. Hopefully that works!
For Anaconda installation of python in windows below solution worked for me
create a batch file with below
"C:\Users\username\Anaconda3\condabin\activate" && python "script.py" &&
deactivate
Setup task to run this batch file

Categories

Resources