3

I have to either store the command line argument in a variable or assign a default value to it.

What i am trying is the below

import sys
Var=sys.argv[1] or "somevalue"

I am getting the error out of index if i don't specify any argument. How to solve this?

Pedro Romano
  • 10,973
  • 4
  • 46
  • 50
pikapika
  • 95
  • 1
  • 2
  • 9

4 Answers4

8
Var=sys.argv[1] if len(sys.argv) > 1 else "somevalue"
5

The builtin argparse module is intended for exactly these sorts of tasks:

import argparse

# Set up argument parser
ap = argparse.ArgumentParser()

# Single positional argument, nargs makes it optional
ap.add_argument("thingy", nargs='?', default="blah")

# Do parsing
a = ap.parse_args()

# Use argument
print a.thingy

Or, if you are stuck with Python 2.6 or earlier, and don't wish to add a requirement on the backported argparse module, you can do similar things manually like so:

import optparse

opter = optparse.OptionParser()
# opter.add_option("-v", "--verbose") etc
opts, args = opter.parse_args()

if len(args) == 0:
    var = "somevalue"
elif len(args) == 1:
    var = args[0]
else:
    opter.error("Only one argument expected, got %d" % len(args))

print var
dbr
  • 165,801
  • 69
  • 278
  • 343
3

Good question.

I think the best solution would be to do

try:
    var = sys.argv[1]
except IndexError:
    var = "somevalue"
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
0

Try the following with a command-line-processing template:

def process_command_line(argv):
    ...
    # add your option here
    parser.add_option('--var',
        default="somevalue",
        help="your help text")

def main(argv=None):
    settings, args = process_command_line(argv)
    ...
    print settings, args # <- print your settings and args

Running ./your_script.py with the template below and your modifications above prints {'var': 'somevalue'} []

For an example of a command-line-processing template see an example in Code Like a Pythonista: Idiomatic Python (http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#command-line-processing):

#!/usr/bin/env python

"""
Module docstring.
"""

import sys
import optparse

def process_command_line(argv):
    """
    Return a 2-tuple: (settings object, args list).
    `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
    """
    if argv is None:
        argv = sys.argv[1:]

    # initialize the parser object:
    parser = optparse.OptionParser(
        formatter=optparse.TitledHelpFormatter(width=78),
        add_help_option=None)

    # define options here:
    parser.add_option(      # customized description; put --help last
        '-h', '--help', action='help',
        help='Show this help message and exit.')

    settings, args = parser.parse_args(argv)

    # check number of arguments, verify values, etc.:
    if args:
        parser.error('program takes no command-line arguments; '
                     '"%s" ignored.' % (args,))

    # further process settings & args if necessary

    return settings, args

def main(argv=None):
    settings, args = process_command_line(argv)
    # application code here, like:
    # run(settings, args)
    return 0        # success

if __name__ == '__main__':
    status = main()
    sys.exit(status)
wolfrevo
  • 6,651
  • 2
  • 26
  • 38