import subprocess
p = subprocess.Popen(["ps", "-a"], stdout=subprocess.PIPE)
out, err = p.communicate()
if ('Httpd' in str(out)):
print('Httpd running')
if ('mysql' in str(out)):
print('mysql running')
import os
import subprocess
def is_service_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
if not is_service_running('mysql'):
print 'mysql is not running'
6条答案
按热度按时间2w3rbyxf1#
Python程序将检查服务是否正在运行。如果它正在运行,输出将是“活动的”,否则输出将是“不活动的”。
希望对你有帮助!!
i7uq4tfw2#
使用psutils类。它很棒,跨平台。下面是函数用法。
okxuctiv3#
您可以使用命令模块来运行ps shell参数:
[edit]我刚刚读了一下commands模块,虽然运行良好,但似乎从Python 2.6开始就不推荐使用它了,甚至在Python 3.x中被删除了。所以如果你使用Python 3,或者想为将来移植到Python 3做好准备,你可以使用subprocess模块:
iszxjhcz4#
如果您使用子进程模块,则可以在不生成shell的情况下执行此操作,而命令模块将生成shell。(您可能不需要为此使用单独的shell,并且这样做可能会存在一些安全问题)。
请注意,这也让您可以对错误采取行动(请参阅下面的err变量),例如,您可以尝试重新启动已关闭的服务等。
http://docs.python.org/2/library/subprocess.html
uubf1zoe5#
如果您的服务已正确注册并且支持
status
报告(init脚本或upstart作业),请使用linux命令如果服务正在运行,命令将返回退出代码
0
os.devnull
是一个额外的函数,它可以隐藏子进程的输出。mcvgt66p6#
我使用了Jossef的代码并添加了一些特性
非常感谢Jossef