Python的:逻辑在不启动的服务,如果它的运行

问题描述 投票:0回答:1

这是一种与我以前的question,但我已经把它变成它自己的问题,因为我觉得这是在它自己的权利有效的问题。

我有以下蟒蛇如果httpd服务失败,将停止radiusd服务。这背后的原因是细节

import os
import subprocess
import time


def running(name):
    with open(os.devnull, 'wb') as hide_output:
        exit_code = subprocess.Popen(['service', name, 'status'], stdout=hide_output, stderr=hide_output).wait()
        return exit_code == 0

while True:
    if not running('radiusd'):
        os.system('service httpd stop')

    if running('radiusd'):
        os.system('service httpd start')

    time.sleep(10)

首先,我在一个永远的循环中运行这一点,并曾计划在.bashrc或东西在启动时运行它。因此,每隔10秒就会运行。这在概念很好,但有没有更好的办法把它每隔几秒钟轮询,而不使用cron作业?

其次,我不喜欢它是如何尝试启动即使它运行的服务。在目前的形式,它只是运行service httpd start每10秒,如果一切都很好。这似乎是系统和一点每个人的时间/精力的浪费上征税。必须有它只是尝试启动过程中,如果它尚未运行的方式。

python subprocess
1个回答
0
投票

有时候,如果只是帮助写下你所面临的问题。正如我在输入上面的,我意识到一个简单的方法来实现它是只添加相反并列的条件语句这样:

import os
import subprocess
import time


def running(name):
    with open(os.devnull, 'wb') as hide_output:
        exit_code = subprocess.Popen(['service', name, 'status'], stdout=hide_output, stderr=hide_output).wait()
        return exit_code == 0

while True:
    if not running('radiusd'):
        if running('httpd'):
            os.system('service httpd stop')

    if running('radiusd'):
        if not running('httpd'):
            os.system('service httpd start')

    time.sleep(10)
© www.soinside.com 2019 - 2024. All rights reserved.