【问题标题】:script with python to verify apache status使用 python 验证 apache 状态的脚本
【发布时间】:2019-09-20 17:08:37
【问题描述】:

我需要制作一个脚本来检查apache2是否工作,如果是,它会给出确认消息,如果不是,它会启动apache2,问题是我的脚本在需要启动apache时出错,但是它当 apache2 已经启动时工作。

这是一个linux服务器,只是为了启动apache,但我是新手

    services = ['apache2']
    for service in services:
            status = subprocess.check_output("/etc/init.d/"+service+" status", shell=True)
            if ("is stopped" in status):
                    print service + "  - Stopped"
                    print service + "  - Trying to start"
                    service_start = subprocess.check_output("/etc/init.d/"+service+" start", shell=True)
            else:
                    print service + "  - Running "

错误信息是:

status = subprocess.check_output("/etc/init.d/"+service+" status", shell=True)
File "/usr/lib/python2.7/subprocess.py", line 223, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '/etc/init.d/apache2 status' returned non-zero exit status 3

【问题讨论】:

    标签: python linux apache2


    【解决方案1】:

    check_output进程返回值不为0时引发异常,需要用try except语句包装调用

    import subprocess
    
    services = ['apache2']
    for service in services:
        try:
            status = subprocess.check_output("/etc/init.d/"+service+" status", shell=True)
        except subprocess.CalledProcessError as e:
            status = "is stopped"
    
            if ("is stopped" in status):
                    print service + "  - Stopped"
                    print service + "  - Trying to start"
                    service_start = subprocess.check_output("/etc/init.d/"+service+" start", shell=True)
            else:
                    print service + "  - Running "
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      相关资源
      最近更新 更多