How can I pass a list as a command-line argument with argparse

Passing lists arsenic bid-formation arguments is a communal project successful Python, particularly once dealing with scripts that necessitate versatile enter. argparse, Python’s constructed-successful module for parsing bid-formation arguments, provides elegant options for dealing with this, permitting you to make person-affable and sturdy bid-formation interfaces. Mastering this method enhances your scripting capabilities, making your packages much versatile and adaptable to assorted situations. This article explores the antithetic methods to accomplish this, focusing connected readability, ratio, and champion practices.

Utilizing nargs for Database Enter

The about easy attack includes the nargs statement inside the add_argument relation of argparse. nargs controls however galore arguments are consumed for a fixed action. Mounting nargs=’’ permits you to seizure immoderate figure of arguments, together with zero, into a database. This is perfect for conditions wherever the person mightiness supply a adaptable figure of gadgets.

For illustration, see a book that processes filenames: python import argparse parser = argparse.ArgumentParser(statement=“Procedure records-data.”) parser.add_argument(“filenames”, nargs="", aid=“Database of filenames to procedure”) args = parser.parse_args() mark(args.filenames) Moving this with python book.py file1.txt file2.txt file3.txt volition shop [‘file1.txt’, ‘file2.txt’, ‘file3.txt’] successful args.filenames.

Utilizing nargs=’+’ plant likewise however requires astatine slightest 1 statement, elevating an mistake if no are supplied. This ensures that your book has astatine slightest any information to run connected.

Append Act for Aggregate Database Appends

The append act permits you to specify an action aggregate instances, accumulating the values into a database. This is utile for situations similar accumulating aggregate flags oregon accumulating values crossed antithetic action invocations.

Illustration: python import argparse parser = argparse.ArgumentParser() parser.add_argument("–numbers", act=“append”, kind=int, aid=“Adhd a figure to the database”) args = parser.parse_args() mark(args.numbers) Calling python book.py –numbers 1 –numbers 2 –numbers three volition consequence successful [1, 2, three] saved successful args.numbers.

This attack presents much power complete however the database is constructed, particularly utile once dealing with optionally available arguments that mightiness beryllium repeated.

Customized Kind Conversions with argparse

For much analyzable database constructions, you tin leverage customized kind conversions. This permits you to parse comma-separated values oregon another specialised codecs straight into lists.

Illustration:

python import argparse def comma_separated_list(drawstring): instrument [int(point) for point successful drawstring.divided(’,’)] parser = argparse.ArgumentParser() parser.add_argument("–values", kind=comma_separated_list, aid=“Comma-separated database of values”) args = parser.parse_args() mark(args.values) Moving python book.py –values 1,2,three volition parse the enter drawstring and make the database [1, 2, three] successful args.values. This attack is extremely adaptable, permitting you to grip assorted database codecs with customized parsing logic.

Precocious Strategies: Combining Approaches

You tin harvester these methods for equal much flexibility. For case, utilizing nargs=’’ with a customized kind permits you to judge aggregate comma-separated lists:

python import argparse def comma_separated_list(drawstring): instrument [int(point) for point successful drawstring.divided(’,’)] parser = argparse.ArgumentParser() parser.add_argument("–values", kind=comma_separated_list, nargs=’’, aid=“Aggregate comma-separated lists”) args = parser.parse_args() mark(args.values) Moving python book.py –values 1,2,three four,5,6 volition consequence successful [[1, 2, three], [four, 5, 6]].

[Infographic Placeholder: Visualizing the antithetic nargs choices and however they contact database instauration]

  • Usage nargs=’’ for zero oregon much arguments.
  • Usage nargs=’+’ for 1 oregon much arguments.
  1. Import the argparse module.
  2. Make an ArgumentParser entity.
  3. Usage add_argument with nargs oregon act=“append”.
  4. Call parse_args() to procedure the arguments.

Selecting the correct methodology relies upon connected your circumstantial wants. For elemental lists, nargs is normally adequate. For repeated choices, append is much due. Customized varieties supply eventual flexibility for analyzable situations. By knowing these strategies, you tin make strong and adaptable bid-formation interfaces for your Python scripts. Larn much astir argparse module. Besides cheque this StackOverflow thread for assemblage insights.

Sojourn Existent Python’s tutorial connected argparse for a much successful-extent usher connected bid-formation statement parsing.

Larn much astir Python ScriptingOften Requested Questions

Q: However bash I grip elective database arguments?

A: Usage nargs=’’ which permits for zero arguments, efficaciously making the database elective. Alternatively, you tin fit a default worth to an bare database.

Efficaciously processing lists arsenic bid-formation arguments enhances the usability and flexibility of your Python scripts. By knowing the nuances of nargs, append, and customized kind conversions inside the argparse module, you tin make cleanable, businesslike, and sturdy bid-formation interfaces. This empowers you to grip divers enter situations and make almighty instruments. Research these strategies, experimentation with antithetic approaches, and detect the champion options for your circumstantial necessities.

Question & Answer :
I americium making an attempt to walk a database arsenic an statement to a bid formation programme. Is location an argparse action to walk a database arsenic action?

parser.add_argument('-l', '--database', kind=database, act='shop', dest='database', aid='<Required> Fit emblem', required=Actual) 

Book is known as similar beneath

python trial.py -l "265340 268738 270774 270817" 

Abbreviated Reply

Usage the nargs action oregon the 'append' mounting of the act action (relying connected however you privation the person interface to behave).

nargs

parser.add_argument('-l','--database', nargs='+', aid='<Required> Fit emblem', required=Actual) # Usage similar: # python arg.py -l 1234 2345 3456 4567 

nargs='+' takes 1 oregon much arguments, nargs='*' takes zero oregon much.

append

parser.add_argument('-l','--database', act='append', aid='<Required> Fit emblem', required=Actual) # Usage similar: # python arg.py -l 1234 -l 2345 -l 3456 -l 4567 

With append you supply the action aggregate occasions to physique ahead the database.

Don’t usage kind=database!!! - Location is most likely nary occupation wherever you would privation to usage kind=database with argparse. Always.


Agelong Reply

Fto’s return a expression successful much item astatine any of the antithetic methods 1 mightiness attempt to bash this, and the extremity consequence.

import argparse parser = argparse.ArgumentParser() # By default it volition neglect with aggregate arguments. parser.add_argument('--default') # Telling the kind to beryllium a database volition besides neglect for aggregate arguments, # however springiness incorrect outcomes for a azygous statement. parser.add_argument('--database-kind', kind=database) # This volition let you to supply aggregate arguments, however you volition acquire # a database of lists which is not desired. parser.add_argument('--database-kind-nargs', kind=database, nargs='+') # This is the accurate manner to grip accepting aggregate arguments. # '+' == 1 oregon much. # '*' == zero oregon much. # '?' == zero oregon 1. # An int is an specific figure of arguments to judge. parser.add_argument('--nargs', nargs='+') # To brand the enter integers parser.add_argument('--nargs-int-kind', nargs='+', kind=int) # An alternate manner to judge aggregate inputs, however you essential # supply the emblem erstwhile per enter. Of class, you tin usage # kind=int present if you privation. parser.add_argument('--append-act', act='append') # To entertainment the outcomes of the fixed action to surface. for _, worth successful parser.parse_args()._get_kwargs(): if worth is not No: mark(worth) 

Present is the output you tin anticipate:

$ python arg.py --default 1234 2345 3456 4567 ... arg.py: mistake: unrecognized arguments: 2345 3456 4567 $ python arg.py --database-kind 1234 2345 3456 4567 ... arg.py: mistake: unrecognized arguments: 2345 3456 4567 $ # Quotes received't aid present... $ python arg.py --database-kind "1234 2345 3456 4567" ['1', '2', 'three', 'four', ' ', '2', 'three', 'four', '5', ' ', 'three', 'four', '5', '6', ' ', 'four', '5', '6', '7'] $ python arg.py --database-kind-nargs 1234 2345 3456 4567 [['1', '2', 'three', 'four'], ['2', 'three', 'four', '5'], ['three', 'four', '5', '6'], ['four', '5', '6', '7']] $ python arg.py --nargs 1234 2345 3456 4567 ['1234', '2345', '3456', '4567'] $ python arg.py --nargs-int-kind 1234 2345 3456 4567 [1234, 2345, 3456, 4567] $ # Antagonistic numbers are dealt with absolutely good retired of the container. $ python arg.py --nargs-int-kind -1234 2345 -3456 4567 [-1234, 2345, -3456, 4567] $ python arg.py --append-act 1234 --append-act 2345 --append-act 3456 --append-act 4567 ['1234', '2345', '3456', '4567'] 

Takeaways:

  • Usage nargs oregon act='append'
    • nargs tin beryllium much simple from a person position, however it tin beryllium unintuitive if location are positional arguments due to the fact that argparse tin’t archer what ought to beryllium a positional statement and what belongs to the nargs; if you person positional arguments past act='append' whitethorn extremity ahead being a amended prime.
    • The supra is lone actual if nargs is fixed '*', '+', oregon '?'. If you supply an integer figure (specified arsenic four) past location volition beryllium nary job mixing choices with nargs and positional arguments due to the fact that argparse volition cognize precisely however galore values to anticipate for the action.
  • Don’t usage quotes connected the bid formation1
  • Don’t usage kind=database, arsenic it volition instrument a database of lists
    • This occurs due to the fact that nether the hood argparse makes use of the worth of kind to coerce all idiosyncratic fixed statement you your chosen kind, not the combination of each arguments.
    • You tin usage kind=int (oregon any) to acquire a database of ints (oregon any)

1: I don’t average successful broad.. I average utilizing quotes to walk a database to argparse is not what you privation.