Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sys.argv arguments optional?

sys.argv takes arguments at the shell command line when running a program. How do I make these arguments optional?

I know I can use try - except. But this forces you to insert either no extra arguments or all extra arguments, unless you nest more try - except which makes the code look much less readable.

Edit

Suppose I would want the following functionality, how do I implement this?

$ python program.py add Peter 
'Peter' was added to the list of names.

This add argument (and not --add) is optional such that

$ python program.py

just runs the program normally.

like image 620
Bentley4 Avatar asked Aug 07 '12 20:08

Bentley4


People also ask

How can you make an input argument optional?

You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function. To learn more about coding in Python, read our How to Learn Python guide .

How do you indicate optional arguments?

To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.

How do you make an argument optional in Python?

A type of argument with a default value is a Python optional parameter. A function definition's assignment operator or the Python **kwargs statement can be used to assign an optional argument. Positional and optional arguments are the two sorts of arguments that a Python function can take.

What makes an argument optional in command line?

Conventions for command-line arguments Optional command-line arguments have a dash ( - ) before them. In general, if an argument doesn't have a dash in front of it, it's not optional unless it's an argument to another command-line argument (see below).


2 Answers

EDIT to address your edit,

import sys

sys.argv = sys.argv[1:]
names = []
while sys.argv and sys.argv[0] == 'add':
    #while the list is not empty and there is a name to add
    names.append(sys.argv[1])
    print sys.argv[1], 'was added to the list of names.'
    sys.argv = sys.argv[2:]

all of the following work with this

$ python program.py add Peter
Peter was added to the list of names.

$ python program.py add Peter add Jane
Peter was added to the list of names.
Jane was added to the list of names.

$ python program.py

if the advantage to requiring 'add' before each name is that if there are any other arguments you want to look for after adding names, you can. If you want to pass multiple names by saying python program.py add Peter Jane this can be done with a fairly simple change

import sys

names = []
if len(sys.argv) > 2 and sys.argv[1] == 'add':
    names = sys.argv[2:]

for n in names:
    print n, 'was added to the list of names.'

ORIGINAL

it seems like you would be better off with something like optparse. However since sys.argv is a list you can check the length of it.

arg1 = sys.argv[1] if len(sys.argv) > 1 else 0 # replace 0 with whatever default you want
arg2 = sys.argv[2] if len(sys.argv) > 2 else 0

and then use arg1 and arg2 as your "optional" command line arguments. this will allow you to pass 1, 2, or 0 command line arguments (actually you can pass more than 2 and they will be ignored). this also assumes that the arguments have a known order, if you want to use flags like -a followed by a value, look into optparse http://docs.python.org/library/optparse.html?highlight=optparse#optparse

like image 64
Ryan Haining Avatar answered Oct 16 '22 10:10

Ryan Haining


plac is an alternative to the standard library modules given in the other answers. It allows to define command line arguments through annotations. From the documentation, exemple 8 demonstrate optional arguments syntax :

example8.py
def main(command: ("SQL query", 'option', 'q'), dsn):
    if command:
        print('executing %s on %s' % (command, dsn))
        # ...

if __name__ == '__main__':
    import plac; plac.call(main)

Argparse exemple :

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--add", help="Add prefix to string")
args = parser.parse_args()

Note that the convention is for optional argument to be provided as "--add" while subcommands are provided as "add". There is a subcommand implementation in argparse.

like image 35
Nicolas Barbey Avatar answered Oct 16 '22 11:10

Nicolas Barbey