I have a batch script that runs a python script:
@echo off
:: Get the directory of the batch script using relative path
set SCRIPT_DIR=%~dp0
set PYTHON_SCRIPT=%SCRIPT_DIR%file_handlers.py
:: Run the Python script
start python "%PYTHON_SCRIPT%" %*
:: Close terminal
exit
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
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 the terminal will stay open forever (exit
will never be executed) because in the python script I run an infinite loop in order to keep the observer alive.
I need a command that I can run in batch script allowing me to close the terminal without killing the process, or basically any solution that will both close terminal and keep observer alive. Possible?
Additional Notes:
-
Implementation is meant to be run on Windows Server 2016 system or later.
-
I had originally implemented this by usign
pywin32
library, specificallywin32serviceutil.ServiceFramework
. In that case I installed aservice_run.py
script
and configured aServiceFramework
inherited class that started theElaborationFolderWatcher
when service is started, then configured service to run at start.That would indeed allow me to bypass this “opened-terminal” issue as no terminal window would open at all in this scenario, BUT I probably need to switch to the execution of the python file through.bat
script for reason I’m not going to explain here directly.