![](/img/trans.png)
[英]JupyterLab - how to find out which python venv is my session running on?
[英]how to find out with python on ubuntu if MySQL is running?
在Ubuntu上,此命令行:
sudo netstat -tap | grep mysql
如果MySQL正在运行,则返回如下内容:
tcp 0 0 localhost:mysql *:* LISTEN 6732/mysqld
如果不是,什么也没有。
我正在使用子进程从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),当我在命令行中运行此命令时-有时会要求输入root密码。 如何通过python脚本传递密码?
尝试行此。
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."
我的机器上的输出 :
['tcp4', '0', '0', '*.mysql', '*.*', 'LISTEN']
OK - MySQL is running.
这里的想法是您执行常规的netstat,并收集所有数据。 然后使用该子过程中的stdout作为下一个子过程的stdin,并在那里执行grep。
这是在Ubuntu 12.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."
为什么不看看是否可以在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.