开发者

get formated output from mysql via python

Hi I want the following output from my query:

OK|Abortedclients=119063 Aborted_connects=67591 Binlog_cache_disk_use=0

But I dont know how to generate it. this is my script:

#!/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()

this is what I get now:

OK|
Aborted_开发者_开发知识库clients=119063
Aborted_connects=67591
Binlog_cache_disk_use=0


You can print the rows together in one string:

output = []
for row in rs:
   output.append('%s=%s' % (row[0], row[1])

print ''.join(output)


Build the string using join:

print('OK|'+' '.join(['{0}={1}'.format(*row) for row in rs]))

' '.join(iterable) creates a string out of the strings in iterable, joined together with a space ' ' in between the strings.


To fix the code you posted with minimal changes, you could add a comma at the end of the print statements:

print "OK|",
for row in rs:
    print "%s=%s" % (row[0], row[1]),

This suppresses the automatic addition of a newline after each print statement. It does, however, add a space (which is not what you said you wanted):

OK| Aborted_clients=0 ...


Join each pair with '=' and then each result with ' ', appended to 'OK|':

'OK|' + (' '.join(['='.join(r) for r in rs]))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜