我在打印带有终端表的表时遇到问题。
这是我的主要剧本:
from ConfigParser import SafeConfigParser
from terminaltables import AsciiTable
parser = SafeConfigParser()
parser.read('my.conf')
for section_name in parser.sections():
description = parser.get(section_name,'description')
url = parser.get(section_name,'url')
table_data = [['Repository', 'Url', 'Description'], [section_name, url, description]]
table = AsciiTable(table_data)
print table.table
这是配置文件my.conf
:
[bug_tracker]
description = some text here
url = http://localhost.tld:8080/bugs/
username = dhellmann
password = SECRET
[wiki]
description = foo bar bla
url = http://localhost.tld:8080/wiki/
username = dhellmann
password = SECRET
这会打印出每个条目的表格,如下所示:
+-------------+---------------------------------+------------------------+
| Repository | Url | Description |
+-------------+---------------------------------+------------------------+
| bug_tracker | http://localhost.foo:8080/bugs/ | some text here |
+-------------+---------------------------------+------------------------+
+------------+---------------------------------+-------------+
| Repository | Url | Description |
+------------+---------------------------------+-------------+
| wiki | http://localhost.foo:8080/wiki/ | foo bar bla |
+------------+---------------------------------+-------------+
但我想要的是:
+-------------+---------------------------------+------------------------+
| Repository | Url | Description |
+-------------+---------------------------------+------------------------+
| bug_tracker | http://localhost.foo:8080/bugs/ | some text here |
+-------------+---------------------------------+------------------------+
| wiki | http://localhost.foo:8080/wiki/ | foo bar bla |
+-------------+---------------------------------+------------------------+
如何修改脚本以获得此输出?
答案 0 :(得分:2)
问题是您在循环的每次迭代中重新创建table_data
和table
。您在每次迭代时打印,然后丢弃旧数据并从头开始新表。您正在创建的表格正文中没有重叠。
您应该有一个table_data
,从标题开始,然后在打印任何内容之前收集所有表格数据。在循环的每次迭代中添加新条目,并在for循环完成后放置print语句。这是一个例子:
from ConfigParser import SafeConfigParser
from terminaltables import AsciiTable
parser = SafeConfigParser()
parser.read('my.conf')
table_data = [['Repository', 'Url', 'Description']]
for section_name in parser.sections():
description = parser.get(section_name,'description')
url = parser.get(section_name,'url')
table_data.append([section_name, url, description])
table = AsciiTable(table_data)
print table.table
以及它输出的内容:
+-------------+---------------------------------+----------------+
| Repository | Url | Description |
+-------------+---------------------------------+----------------+
| bug_tracker | http://localhost.tld:8080/bugs/ | some text here |
| wiki | http://localhost.tld:8080/wiki/ | foo bar bla |
+-------------+---------------------------------+----------------+
如果你想在bug_tracker和wiki行之间有一个水平规则,那么你需要将table.inner_row_border
设置为True。所以你用以下代码替换最后两行:
table = AsciiTable(table_data)
table.inner_row_border = True
print table.table