用python替换bash脚本-检查进程是否正在运行?

时间:2018-10-08 17:44:27

标签: python bash

这是我目前拥有的(检查多个进程,这只是一个),它神奇地起作用:

if role=Agent
then 
    echo "Validations for the service $servicename..."
        livefilterd=$(pgrep -f backgroundd)
            if [ -n "$livefilterd" ]
                    then
                            printf "The $servicename service is running as: \n$livefilterd"
                                let statusfilterd=1
                    else
                            echo -ne '!!!The $servicename process is NOT running!!!\r';sleep 0.5;echo -ne '   The $servicename process is NOT running   \r';sleep 0.5;echo -ne '!!!The $servicename process is NOT running!!!\r';sleep 0.5;echo -ne '   The $servicename process is NOT running   \r';sleep 0.5;
                                let "badkids=badkids+1"
                                let statusfilterd=0
            fi
else
    print "Validation for $servicename is being skipped as it's not expected on this host due to the role of $role."
fi

我想将其移至python,大部分脚本我都能够弄清楚并进行测试,但是上面的代码块存在问题。这是我到达的地方,但是我不确定是否可以在if / else语句中嵌套try / except,并且会非常感谢您的帮助:

servicename=backgroundd
if role == 'Agent': 
    print ("Validations for the service " + servicename + "...")
try:
    get_pid("backgroundd")    
    print ("YAY")
    print ("The " + servicename + " service is running as:" + servicename)
    statusfilterd = 1
except Exception:
    cprint("\n!!!!The " + servicename + " process is NOT running!!!!", 'red', attrs=['blink'])
    badkids = badkids+1
    statusfilterd = 0
else
    print ("Validation for $servicename is being skipped as it's not expected on this host due to the role of $role.")
print();print();time.sleep(0.5)

我的错误在哪里???提前非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以将try / except嵌套在if / else中,但是您需要注意缩进,因为这就是Python表示代码块的方式。

servicename=backgroundd
if role == 'Agent': 
    print ("Validations for the service " + servicename + "...")
    try:
        get_pid("backgroundd")    
        print ("YAY")
        print ("The " + servicename + " service is running as:" + servicename)
        statusfilterd = 1
    except Exception:
        cprint("\n!!!!The " + servicename + " process is NOT running!!!!", 'red', attrs=['blink'])
        badkids = badkids+1
        statusfilterd = 0
else:
    print ("Validation for $servicename is being skipped as it's not expected on this host due to the role of $role.")
print();print();time.sleep(0.5)