Reputation: 301
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.
Upvotes: 8
Views: 2049
Reputation: 532303
--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']])
Upvotes: 12