J L
J L

Reputation: 319

Is there a way to make python subprocess not terminate after running through the script once?

Consider the following 2 files

script_to_start_other_script.py

import schedule
import time
import subprocess 

def run_again():
    subprocess.call(["bash", "-c", "" + "  nohup python script_to_be_started.py > /dev/null 2>&1&"])  


if __name__== "__main__":

    schedule.every(5).seconds.do(run_again)

    while True:
        schedule.run_pending()
        time.sleep(1)
        pass

script_to_be_started.py

import logging
from logging.handlers import TimedRotatingFileHandler

# Init logger
logger = logging.getLogger('test_log')
hdlr = logging.handlers.TimedRotatingFileHandler('./test_log.log', when='h', interval=10)
formatter = logging.Formatter('%(asctime)s %(levelname)s : %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
logger.info('Beginning of test_log.py')

import schedule

def run_again():
    logger.info('I am being called')

if __name__== "__main__":
    schedule.every(5).seconds.do(run_again)

    while True:
        logger.info('how many time am I being called')  
        schedule.run_pending()
        time.sleep(1)
        pass

Whenever I run script_to_start_other_script.py , script_to_be_started.py will only run the entire script once

logger.info('how many time am I being called')  

will only print once even though there is a while loop. Is there a way for the script to keep running?

Upvotes: 0

Views: 93

Answers (1)

faisal
faisal

Reputation: 353

I tried you first script and it continuously ran the second one. Try to just run the script_to_be_started.py and make sure that it runs fine. One reason that the second script ran until the log statement might be the missing import for time.

import time

So, after printing the log message, the second script will silently crash because of missing import.

I am assuming you only stripped down the logging stuff but the missing import for time is actually part of your code.

Upvotes: 1

Related Questions