python - 设计带有列表的可扩展命令行界面

标签 python command-line-interface

这是我的三个列表:

# made up data
products = ['apple','banana','orange'] 
prices = ['£0.11','£0.07','£0.05']
dates = ['02/04/2017','14/09/2018','06/08/2016']

重要信息

  • 这些列表中的数据将随其大小而变化,但它们将保持相同的数据类型。
  • 每个列表的第一个元素都是链接的,第二个和第三个元素也是如此......

所需的命令行界面:

Product | Price | Date of Purchase
--------|-------|------------------
 apple  | £0.11 |    02/04/2017
--------|-------|------------------
 banana | £0.07 |    14/09/2018
--------|-------|------------------
 orange | £0.05 |    06/08/2016

我想创建一个这样的表。如果每个列表中有更多元素,它显然应该继续,但我不知道如何创建它。

我可以做到

print(""" Product | Price | Date of Purchase   # etc...
          --------|-------|------------------
              %s  |   %s  |     %s 
""" % (products[0],prices[0],dates[0])) 

但我认为这会对界面进行硬编码,这并不理想,因为列表的长度未确定

有什么帮助吗?

最佳答案

如果您想要一个不使用库的版本,这里有一个相当简单的函数,它使用了一些列表推导式

def print_table(headers, *columns):
    # Ignore any columns of data that don't have a header
    columns = columns[:len(headers)]

    # Start with a space to set the header off from the left edge, then join the header strings with " | "
    print(" " + " | ".join(headers))
    # Draw the header separator with column dividers based on header length
    print("|".join(['-' * (len(header) + 2) for header in headers]))

    # Iterate over all lists passed in, and combine them together in a tuple by row
    for row in zip(*columns):
        # Center the contents within the space available in the column based on the header width
        print("|".join([
            col.center((len(headers[idx]) + 2), ' ')
            for idx, col in enumerate(row)
        ]))

这不会处理长于列标题长度 + 2 的单元格值。但是通过截断单元格内容很容易实现(可以看到字符串截断的示例 here )。

关于python - 设计带有列表的可扩展命令行界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953808/

相关文章:

Python - 在数百个大型 gzip 文件中搜索项目

python - 单元测试中的模拟日志处理程序

python - 消息类型 websocket gdax (coinbase)

python - 安装到(非 root)用户帐户后如何找到 python 命令行工具?

python - fcntl.ioctl 在 Python 2 上总是失败

python - 在 glade 中使用文件选择器对话框

grails - 无法使用 Java 11 运行 Grails 4.0.1 cli - 在堆栈跟踪中出现空指针错误

node.js - Readline 争论或如何捕获关键事件并在框内绘制

go - 全局变量不会从 CLI 命令中保留下来

linux - CentOS 7 如何从命令行停止/启动 Gnome 桌面