Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse arguments with repeatable parameter pairs

I'm developing a Python script that will utilize CLI arguments to convert a .xls/.xlsx file into a .csv. Because .xsl/.xlsx files can have multiple sheets, each sheet needs to be individually converted into separate .csv files. What I would like to do is use argparse to add a required parameter to specify which sheet to convert and an optional parameter to specify what the resulting .csv should be named. Here is an example of how I would like the command to look:

python converter.py --sheets <sheet-name> [sheet-rename]

So I'm not sure how to add an argument with two parameters like this using argparse.

Additionally, I would like to add more functionality to this argument. If it's possible, I'd like to make it possible to repeat arguments to allow for more sheets to be converted. I'm not sure how the command syntax would look but something like this:

python converter.py --sheets (<sheet-name> [sheet-rename])...
python converter.py --sheets sheet1 sheet1_rename sheet2 sheet2_rename

This may end up being too complicated but any input would be great.

like image 806
dselgo Avatar asked Jan 20 '17 14:01

dselgo


1 Answers

--sheet can be defined as an option that takes two arguments, both of which are accumulated in a list.

p.add_argument('--sheet', action='append', nargs=2)

Calling python converter.py --sheet old1 new1 --sheet old2 new2 would produce a list of lists:

>>> print p.parse_args("--sheet old1 new1 --sheet old2 new2".split())
Namespace(sheet=[['old1', 'new1'], ['old2', 'new2']])
like image 130
chepner Avatar answered Sep 30 '22 12:09

chepner