1

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 Answers1

3

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

  1. Launch a command prompt.
  2. Associate the correct file group with .py scripts: assoc .py=Python.File
  3. 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"]]
Noah M.
  • 310
  • 1
  • 8
  • That's great! What about when I want to terminate this schedule? Because then, if I have a schedule and can't see the shell it will be a problem to close the program right? – independentvariable Jun 05 '18 at 11:20
  • @aslv95 You can use the `psutil` module to search running processes and find which `python.exe` (or `pythonw.exe`) is your script. – Noah M. Jun 05 '18 at 11:32
  • I used it, that helps! Also I can see the running processes from Task Manager (as Python.exe). One last thing: I want the window to appear only to get input from the user. But with .pyw I don't see the window anytime. Shall I use another package to force the window to stay open until the user gives an input and close until the next scheduled time? – independentvariable Jun 05 '18 at 11:45
  • You could run a different visible script to get user input or you could close the hidden script, open it visibly, get user input, and then re-open it with `pythonw` or `.pyw`. At this point it's up to you. – Noah M. Jun 05 '18 at 12:10