I have been asked to run a python script from the Windows Task Scheduler.
In my python script I will substantially use watchdog library in order to instanciate and run an Observer that will monitor file changes in a specific directory path
file_handlers.py
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from elaboration_directory import FILE_PROCESS_DIR
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class FileHandler(FileSystemEventHandler):
def on_created(self, event):
if not event.is_directory:
file_path = event.src_path
logger.info('File added. File path: "%s"' % file_path)
class ElaborationFolderWatcher(object):
def start(self):
event_handler = FileHandler()
observer = Observer()
observer.schedule(event_handler, path=FILE_PROCESS_DIR, recursive=False)
observer.start()
logger.info('Observer: started')
try:
while True:
# keep observer active
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == '__main__':
logger.info('Python script started')
elaboration_folder_watcher = ElaborationFolderWatcher()
elaboration_folder_watcher.start()
My issue is that when I run the script from the Task Scheduler a terminal will open, and if I close it it will kill the process (and Observers).
Question
How can I run the python script from Windows Task Scheduler without opening any window?
Solution
Possible solution: instead of directly running the file_handlers.py I can run a .bat script that will call the file_handlers.py. By adding the argument pythonw.exe to the start command, no window will be opened.
run_program.bat (Target this file with Task Scheduler action)
@echo off
::Identify the path of directory containing python script using relative path
set SCRIPT_DIR=%~dp0
set PYTHON_SCRIPT=%SCRIPT_DIR%\file_handlers.py
:: Run the Python script. Argument "pythonw.exe" will avoid cmd opening
start "" "pythonw.exe" "%PYTHON_SCRIPT%" %*