您好,我想从我的查询中获得以下输出:
OK|Abortedclients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0
但我不知道如何生成它。这是我的脚本:
#!/usr/bin/env python
import MySQLdb
conn = MySQLdb.connect (host = "...", user="...", passwd="...")
cursor = conn.cursor ()
cursor.execute ("SHOW GLOBAL STATUS")
rs = cursor.fetchall ()
#print rs
print "OK|"
for row in rs:
print "%s=%s" % (row[0], row[1])
cursor.close()
这就是我现在得到的:
OK|
Aborted_clients=119063
Aborted_connects=67591
Binlog_cache_disk_use=0
发布于 2011-10-01 13:11:23
使用join构建字符串
print('OK|'+' '.join(['{0}={1}'.format(*row) for row in rs]))
' '.join(iterable)
在iterable中的字符串之外创建一个字符串,并在字符串之间加入一个空格' '
。
要修复您发布的代码,只需进行最少的更改,您可以在print语句的末尾添加一个逗号:
print "OK|",
for row in rs:
print "%s=%s" % (row[0], row[1]),
这将禁止在每个print语句后自动添加换行符。但是,它确实添加了一个空格(这不是您所说的您想要的):
OK| Aborted_clients=0 ...
发布于 2011-10-01 13:12:19
您可以将行一起打印到一个字符串中:
output = []
for row in rs:
output.append('%s=%s' % (row[0], row[1])
print ''.join(output)
发布于 2011-10-01 13:44:53
用'=‘连接每一对,然后用’‘连接每个结果,并附加在’OK|‘后面:
'OK|' + (' '.join(['='.join(r) for r in rs]))
https://stackoverflow.com/questions/7620360
复制