so I've decided to try to make a nice cmd menu on windows in python, but I got stuck on one of the first things. I want to create a list of commands and then display them in a table.I am using prettytable
to create the tables.
So I would like my output to look like this:
--------- -------------------------------
| Command | Usage |
--------- -------------------------------
| Help | /help |
| Help2 | /help 2 |
| Help3 | /help 3 |
--------- -------------------------------
But I cannot figure out how to create and work with the list. The code currently looks like this
from prettytable import PrettyTable
_cmdTable = PrettyTable(["Command", "Usage"])
#Here I create the commands
help = ['Help','/help']
help = ['Help2','/help2']
help = ['Help2','/help3']
#And here I add rows and print it
_cmdTable.add_row([help[0], help[1]])
_cmdTable.add_row([help2[0], help[1]])
_cmdTable.add_row([help3[0], help[1]])
print(_cmdTable)
But this is way too much work. I would like to make it easier, but I cannot figure out how. I'd imagine it to look something like this:
from prettytable import PrettyTable
_cmdTable = PrettyTable(["Command", "Usage"])
commands = {["Help", "/help"], ["Help2", "/help2"], ["Help3", "/help3"]}
for cmd in commands:
_cmdTable.add_row([cmd])
print(_cmdTable)
I know it's possible, just don't know how. It doesn't have to use the same module for tables, if you know some that's better or fits this request more, use it.
I basically want to make the process easier, not make it manually everytime I add a new command. Hope I explained it clearly. Thanks!
CodePudding user response:
You can have more manual control using string formatting
header = ['Command', 'Usage']
rows = [['Help', '/help'], ['Help2', '/help 2'], ['Help3', '/help 3']]
spacer1 = 10
spacer2 = 20
line = ' ' '-'*spacer1 ' ' '-'*spacer2 ' \n'
header = f'| {header[0]:<{spacer1-1}}|{header[1]:^{spacer2}}|\n'
table_rows = ''
for row in rows:
table_rows = f'| {row[0]:<{spacer1-1}}|{row[1]:^{spacer2}}|\n'
print(line header line table_rows line)
Edit: Added spacing control with variables.
CodePudding user response:
You can't put lists in a set. commands
should either be a list of lists, or a set of tuples. Using a list is probably more appropriate in this application, because you may want the table items in a specific order.
You shouldn't put cmd
inside another list. Each element of commands
is already a list.
commands = [["Help", "/help"], ["Help2", "/help2"], ["Help3", "/help3"]]
for cmd in commands:
_cmdTable.add_row(cmd)