I am using ApScheduler package in Python to schedule a program to run every hour. However, the shell window is never closing and if I manually close it, the program is terminated. Is there a way I can schedule a python program without seeing the window when the code is not running? Also, in .pyw the window is never being shown. So I want the window to be open during the run, and then to be closed until the next run.
1 Answer
If you want to open or hide the window at your leisure, you have to use a GUI package such as TkInter. Then follow this tutorial on how to show or hide a window with TkInter.
If you run the script with pythonw.exe or you save the script as .pyw, the terminal window will be hidden.
You just need to open the job script using pythonw.exe.
Two lines in the command prompt to set all python files to open with it. Python Documentation - 3.3.4 Executing scripts
- Launch a command prompt.
- Associate the correct file group with .py scripts:
assoc .py=Python.File- Redirect all Python files to the new executable:
ftype Python.File=C:\Path\to\pythonw.exe "%1" %*
If you need to close the script but the window is hidden you can use the psutil module to find which executable is running your script, grab the PID, and kill it.
import psutil
scripts = [[" ".join(p.cmdline()), p.pid] for p in psutil.process_iter()
if p.name().lower() in ["python.exe", "pythonw.exe"]]
4 Comments
psutil module to search running processes and find which python.exe (or pythonw.exe) is your script.pythonw or .pyw. At this point it's up to you.