task scheduler thinks python script is still running - python

I have a python script which in turn executes other python scripts.
I put this as a task on WinXP task scheduler. the thing runs - command prompt is opened, sparks are flying, magic happens... eventually the task is completed, I get a nice
'print script ended!!'
and back to prompt. but Task Scheduler thinks the task is still running ! which in turn prevents it from running it again on daily basis.
so I tried making a BAT file which just calls the script:
script.py
echo pyfinished
to my surprise cannot see 'pyfinished' at the end ...

I have this problem as well. What I did to make sure the script stops is configure the task to stop after 1 hour (or however long the script(s) should take). This kills the task and thus when the task schedule comes around again, it has no problem kicking off.
As for why Task Scheduler can't detect the script is finished, I have no idea. It's royally annoying.

a line with os.system('cmd /K script.py') makes the process stay alive until I manually kill it.

Related

Trouble executing Python script with Windows Task Scheduler

Having trouble with Windows Task Scheduler, and didn't find a solution browsing through other questions. We've got several Python Scripts running via Task Scheduler that are all running just fine, but there's one in particular that just won't run.
The "Run whether use is logged in or not" box is checked, as well as the "Run with highest privileges" box, as it is with the ones that are working.
In the Start Program box I have "C:\Program Files\Python310\python.exe" and in the Add Arguments box I have C:\Users\<user>\<dir1>\<dir2>\script.py.
Using cmd, the following runs the program and generates the file I want perfectly, which is just the exact same things as above.
"C:\Program Files\Python310\python.exe" C:\Users\<user>\<dir1>\<dir2>\script.py
I've tried changing the location of the python interpreter, using a different interpreter version, using task scheduler to run CMD first with the above as arguments, and nothing seems to do it.
On every attempt, I get the following:
Task Started (1)
Action started (1)
Action completed (2)
Task completed (2)
And every time this happens, the script hasn't actually run. I even copy/pasted my the bits in task scheduler into CMD to make sure I didn't overlook a typo or something like that.
Thanks in advance!

Stop raspbian/debian from within python

When I am away from my mountain, I monitor my Photo-voltaic system with Raspberry Pi and a small python script to read data and send it to my web page every hour. That is launched by a electo-mechanical switch that lights up the stuff for 15 minutes. But during that period, the script may run twice, which I would like to prevent as the result is messy (lsdx.eu/GPV_ZSDX).
I want to add some line at the end of the script to stop it once it has run once and possibly stop raspbian as well for a clean exit before the power is off.
- "exit" only exits a loop but the script is still running
- of course Ctrl+C won't do as I am away;
Could not find any tip in these highly technical messages in StackOverflow or in Rasbian help either.
Any tip?
Thanks
The exit() command should exit the program (break is the statement that will exit a loop). What behavior are you seeing?
To shut down , try :
python3:
from subprocess import run
run('poweroff', shell=True)
python2:
from subprocess import call
call('poweroff')
Note: poweroff may be called shutdown on your system and might require additional command line switches to force a shutdown (if needed).
For your case, structure the python script as a function using the following construct:
def read_data():
data_reading_voodo
return message_to_be_sent
def send_message(msg):
perform_message_sending_voodo
log_message_sending_voodoo_success_or_failure
return None
if __name__ == "__main__":
msg = read_data()
send_message(msg)
Structured like this, the python script should exit after running.
Next create a shell sript like follows (assuming bash and python, but modify according to your usage)
#!/bin/bash
python -m /path/to/your/voodo/script && sudo shutdown -h 6
The sudo shudown -h 6 shuts down the raspberrypi 6 minutes after the script is run. This option helps so you have some time after startup to remove the sript if you ever want to stop the run-restart cycle.
Make the shell script executable: chmod 755 run_py_script_then_set_shutdown see man chmod for details
Now create a cronjob to run run_py_script_then_set_shutdown on startup.
crontab -e Then add the following line to your crontab
#reboot /path/to/your/shell/script
Save, reboot the pi, and you're done.
Every time the rpi starts up, the python script should run and exit. Then the rpi will shutdown 6 minutes after the python script exits.
You can (should) adjust the 6 minutes for your purposes.
Thanks for all these answers that help me learn Pyth and Deb.
I finally opted for a very simple solution at the end of the script:
import os
os.system('sudo shutdown now')
But I keep in mind these other solutions
Thanks again,
Lionel

Python script never ends in task scheduler

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.
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!
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'
There seems to be no correct fix for such issue with CMD as the intermediate launcher.
There is a [End] command in Task Scheduler GUI, clicking it will always terminate the CMD/batch file leaving the spawned python.exe process to straw.
The real problem: there doesn't seem to be any way for cmd to pass on the terminate signal to python.exe.. and neither can taskengine reliably determine if python.exe is alive or not.
I ran into the same problem, the python file didn't stop in the task scheduler. I imported sys and wrote sys.exit(0) but I still got the same problem.
Finally, I decided to press "Update" which solved my problem; the status of the task was "Ready", and not "Running". For information, I use windows 11.

Shell script to run task and shutdown after task is done

I want to run a shell script that runs a python program and shutdowns after the program is done. Here is what I wrote
#!/bin/bash
python program
sudo shutdown -h now
This just shutdowns the system without waiting for the program to complete. Is there a different command to use that waits for the program to complete?
What you have in your example should actually only shutdown once the python command has completed, unless the python program forks or backgrounds early.
Another way to run it would be to make the shutdown conditional upon the success of the first command
python command && sudo shutdown -h now
Of course this still will not help you if the python program does anything like forking or daemonizing. Simply try running the python script alone and take note if control returns immediately to the console or not.
You could run the command halt to stop your system:
#!/bin/sh
python program
sudo halt
The python program is running first, and halt would run after its completion (you might test the exit code of your python program). If it does not behave like expected, try to understand why. You could add a logger command before the halt to write something in the system logs.
Alternatively, you can use command substitution like this:
$(command to run your program)
The script waits until the wrapped command finishes before moving onto the next one!
#!/bin/sh
$(python program.py)
sudo shutdown -P 0

os.system('exit') in python

My friend is in a macOS environment and he wanted to call os.system('exit') at the end of his python script to make the terminal close. It doesn't. This doesn't surprise me but I would like to know what exactly is going on between the python script and the terminal when this call is made.
In my mental simulation the terminal should have to tell you that there are still running jobs, but that doesn't happen either.
As a side question : will some less common terminals close when a process calls this?
read the help:
Execute the command (a string) in a subshell.
A subshell is launched, and exit is run in that subshell.
To exit the enclosing terminal, you have to kill the parent. One way to do it is:
os.system("kill -9 %d"%(os.getppid())
The system function starts another shell to execute a command. So in this case your Python scripts starts a shell and runs "exit" command in there, which makes that process exit. However, the Python script itself, including a terminal where it is running, continues to run. If the intent is to kill the terminal, you have to get the parent process ID and send a signal requesting it to stop. That will kill both Python script and a terminal.
Remember that system first spawns/forks a sub-shell to execute its commands. In effect, you are asking only the sub-shell to exit.

Categories

Resources