3
votes

I am trying to set up a python code to be executed automatically.

I started with a small code to be executed:

import datetime
with open("out.txt","a") as f:
    f.write(datetime.datetime.now().isoformat())

The task will start allright, and executes (The file is modified), but it never ends in the task scheduler.

this and this exist in SO, but have no real answer. The only workaround proposed in these threads is to force the end of task after a given time in Windows, but this requires to know how long the python script will take which will not be the case for my actual task.

How can the task scheduler know that a python script is finished ?

I run it the following way in the task scheduler :

  • program : cmd

  • arguments : /c C:\python27\python.exe C:\path\of\script.py

  • execute in : C:\path\of\

I tried some variations around this, like executing python instead of cmd, but it didn't change anything. I had hoped the /c would force the task to close.

2
I wonder if it would terminate if you explicitly close the file afterwards.John Messenger
exit status 0 represents successful completion of any task. try adding sys.exit(0) in the end, also close the file pointer before exit.Gaurav Pundir
Thanks for your suggestions, I added f.close() and sys.exit(0) to my code, but it didn't modify the issue : task still stays as "Running" when I launch it from task schedulerWNG

2 Answers

1
votes

as Gaurav Pundir mentioned, adding sys.exit(0) should end the script properly and thus the task. However, you do need to add the sys library with import sys in order to use sys.exit(0). Hope this helps!

0
votes

it looks like a bug to me. Try looking up for python console under Task Manager. if it is not there then the program has exited successfully.

I have the same issue with Windows 10, python script ran successfully, there is no python console under Task Manager, yet the scheduled task Status still says 'Running'