如果MySQL正在运行,如何在ubuntu上找到python?

2024-10-01 11:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在Ubuntu上这个命令行:

sudo netstat -tap | grep mysql

如果MySQL正在运行,则会返回类似以下内容:

^{pr2}$

如果不是的话也没什么。在

我使用subprocess从python代码中找出MySQL是否启动了,方法是在netstat返回的内容中查找“LISTEN”,这样做:

import subprocess

msqlr = subprocess.Popen(["sudo netstat -tap | grep mysql"], stdout=subprocess.PIPE).communicate()[0]
msqlrLines = msqlr.split("\n")
vals = msqlrLines[0].split()
print "vals[0] : %s" % vals[0]
if vals[0][-2] == "LISTEN":
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."

当我运行这个程序时,它返回:

OSError: [Errno 2] No such file or directory

在同一时间子流程.Popen... 我用一个词来论证(比如说“df”)——它很好用。如果参数不止一个单词(例如“df-h/”或者,像这里的“sudo netstat-tap | grep mysql”)——我得到了“没有这样的文件或目录”错误。在

以及相关问题(#2),当我在命令行中运行这个命令时,有时它会要求输入根密码。如何从python脚本传递密码?在


Tags: 命令行mysqlsudotapgreplistensplitsubprocess
2条回答

为什么不看看能否用python连接:

try:

    con = _mysql.connect('localhost', 'user', 
        'password', 'testdb')

except _mysql.Error, e:

print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)

试试这个。在

import subprocess
import string

msqlr = subprocess.Popen("sudo /usr/sbin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/usr/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."

在我的机器上输出

^{pr2}$

这里的想法是你做普通的netstat,并收集所有的数据。然后使用该子代码中的stdout作为下一个子代码的stdin,并在那里执行grep。在

下面是一个在Ubuntu12.04上运行的示例

import subprocess
import string

msqlr = subprocess.Popen("sudo /bin/netstat -al".split(), stdout=subprocess.PIPE).stdout
grep = subprocess.Popen(["/bin/grep", "mysql"], stdin=msqlr, stdout=subprocess.PIPE).stdout
msqlrLines = grep.read().split("\n")
vals = map(string.strip, msqlrLines[0].split())
print vals
if len(vals) and vals[-1] in ("LISTENING", "LISTEN"):
    print "OK - MySQL is running."
else:
    print "Not OK - MySQL is not running."

相关问题 更多 >