25
from sys import argv
script, lira_cbt, [eur_hedge] = argv

if eur_hedge == None:
    #Do x
else:
    #Do y

I want it to be able to run with just lira_cbt as an argument (doing x), or with both lira_cbt and eur_hedge (doing y). Can this be achieved with sys.argv?

1
  • 1
    If your CLI gets that complex, you should probably start using argparse (or optparse if you're stuck with some older version). Commented Feb 25, 2012 at 10:01

6 Answers 6

32

Just use the length of sys.argv

if len(sys.argv) == 2:
  # do X
else:
  # do Y
Sign up to request clarification or add additional context in comments.

1 Comment

Can this be done if the length of sys.argv is only ever going to be 0 or 1?
8

If this is to be part of more than a throw-away script, consider using argparse http://docs.python.org/library/argparse.html

At the moment it will be much more complicated, but it will help you keep documented the options your program accepts and also provide useful error messages unlike a "too many values to unpack" that the user might not understand.

Comments

4

Another option is to extract the values from the argv list using try:

lira_cbt = sys.argv[1]
try:
  eur_hedge = sys.argv[2]
except IndexError:
  eur_hedge = None

if eur_hedge == None:
    # Do X
else:
    # Do Y

You could also take a look at getopt for a more flexible parser of command line arguments.

1 Comment

optparse or argparse would be much better than getopt!
2

You can simply check the length of sys.argv.

if len(sys.argv) < 2:
    # Error, not enough arguments

lira_cbt = sys.argv[1]
if len(sys.argv) == 2:
    # Do X
else:
    eur_hedge = sys.argv[2]
    # Do Y

2 Comments

But no way to specifically pull the value in eur_hedge without throwing up a need more/too many variable to unpack argument?
No, there is no way to do it, unless you want to convert it to a function call and use something like def main(script, lira_cbt, eur_hedge=None) and main(*sys.argv), which I definitely wouldn't do.
0

If I may suggest an alternative approach:

from sys import argv
option_handle_list = ['--script', '--lira_cbt', '--eur_hedge']
options = {}
for option_handle in option_handle_list:
    options[option_handle[2:]] = argv[argv.index(option_handle) + 1] if option_handle in argv else None
if options['eur_hedge'] == None:
    #Do x
else:
    #Do y

2 Comments

While this may work, using a module like argparse for this task would be both easier and more pythonic.
@YSelf I am not debating on the easier / more traditional solution. Just answering the original question.
0

Here is a simple example that tries to read the argv1 input but does something else if one isn't provided.

from sys import argv

try:
    x = argv[1]
    print("x" + " Was given as an argument")
except:
    print("No Input Provided")

Console Output

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.