I'm trying to debug a python script using logger. It opens another python script and checks whether it's running or not. If not then it restarts that script.
My script:
while True:
print("Restart")
logger.info("Restart")
try:
p = subprocess.Popen(["python", OPEN_FILE]).wait()
except:
logger.exception("Error opening script")
print("Exit")
logger.error("Exit")
time.sleep(10)
if p != 0:
continue
else:
break
If file is not found then it prints error on terminal:
pi@raspberrypi:~/Desktop/MODBUS_TCP $ sudo python py_restart_script.py
Restart
python: can't open
file'/home/pi/Desktop/MODBUS_TCP/API_Modbus_TCP_Server3.py': [Errno 2] No
such file or directory
Exit
But that error is not in the log file:
2018-11-15 22:30:16,269 - INFO - Restart
2018-11-15 22:30:16,325 - ERROR - Exit
How to log same error showing in terminal to the log file?
except Exception as exc:and then use something likelogger.error(str(exc))to record it in the log file.restart.pyscript. It's happening in the spawned process which is running a separate copy of the python interpreter and the failure to be able to do that is just the return of a non-zero status code. @isalgueiro's answer should allow you to detect and capture the error output from that happening and put it in the log.