I have started a python script in nohup. The script contains a finally block which will print the remaining items in the queue to print into a log file, if any Exception OR Keyboard interrupt occurs.
It is working fine as long as I'm in the same shell from where I executed the script. For eg: below steps are working as I have expected.
# Run the script in the background with nohup
nohup script_name.py > script_name.log 2>&1 &
# List the processes currently running in the background
jobs
# Bring back the process to foreground
fg 1
# Send Keyboard interrupt to stop the process by allowing to execute finally code block
Press CTRL+C
The script prints all the pending items in the queue to the "script_name.log" file.
But the problem is, once I exit the current shell from where I have started the "nohup" process, I can no longer bring that process back to foreground to send Keyboard interrupt.
At the same time, if I use kill PROCESS_ID command, it is not allowing the finally block to execute, so I'm also loosing the pending items in the queue.
Is there is any way I can terminate the process OR send a Keyboard interrupt to nohup process, still by allowing finally block to execute the code?
Thank you.
UPDATED: High level python code: It is actually a Python project with lot of directories and other scripts but let me give only the finally block part of the code here.
try:
cc = crawler.MultiThreadedWebCrawler(max_workers)
cc.run_web_crawler()
finally:
cc.info(script_start_time)
# Inside another script, the definition of "info" method is,
def info(self, script_start_time):
print('\n', self.crawl_queue.qsize(), ' URLs in crawl_queue are:\n')
while self.crawl_queue.qsize() > 0:
print(self.crawl_queue.qsize(), ' ', self.crawl_queue.get(), '\n')
print("Script execution started at ", script_start_time)
print("Script execution ended at ", datetime.now().strftime('%Y-%m-%d__%H_%M_%S'))