有没有办法让python子进程在运行脚本一次后不终止



考虑以下 2 个文件

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

每当我运行script_to_start_other_script.py时,script_to_be_started.py只会运行一次整个脚本

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

即使有一个 while 循环,也只会打印一次。有没有办法让脚本继续运行?

我尝试了你的第一个脚本,它连续运行第二个脚本。尝试只运行script_to_be_started.py并确保它运行正常。第二个脚本运行到日志语句的一个原因可能是缺少时间导入。

import time

因此,在打印日志消息后,第二个脚本将因缺少导入而静默崩溃。

我假设您只删除了日志记录内容,但缺少时间导入实际上是您代码的一部分。

最新更新