简体   繁体   English

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

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

Consider the following 2 files 考虑以下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

Whenever I run script_to_start_other_script.py , script_to_be_started.py will only run the entire script once 每当我运行script_to_start_other_script.pyscript_to_be_started.py将只运行整个脚本一次

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

will only print once even though there is a while loop. 即使有while循环,也只会打印一次。 Is there a way for the script to keep running? 有没有办法让脚本继续运行?

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. 尝试仅运行script_to_be_started.py并确保其运行正常。 One reason that the second script ran until the log statement might be the missing import for time. 第二个脚本一直运行到log语句的原因之一可能是时间丢失。

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. 我假设您只删除了日志记录内容,但是丢失的时间导入实际上是代码的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM