2011-10-01 47 views
0

您好我想從我的查詢下面的輸出從MySQL獲得格式化輸出:通過Python

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 

回答

0

構建使用join字符串:

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

' '.join(iterable)在迭代創建一個字符串出字符串,將兩個字符串之間的空格' '連接在一起。


要解決您發佈最小的變化代碼,你可以在打印報表的末尾添加一個逗號:

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

這抑制了自動添加一個換行符的每個打印語句之後。 它,然而,添加一個空格(這是你說的不是你想要的):

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

print ''.join(output) 
+0

感謝的人,我會測試它 –

0

您可以集中在一個字符串打印的行「然後每個結果與」」,追加到‘OK |’:

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

加入每一對使用「=:

OK| Aborted_clients=0 ... 
+0

它解決了我的prob.thanks –