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?

s4w3d0ff
  • 1,091
  • 10
  • 24
Felix
  • 831
  • 4
  • 12
  • 16
  • 1
    If your CLI gets that complex, you should probably start using `argparse` (or `optparse` if you're stuck with some older version). –  Feb 25 '12 at 10:01

6 Answers6

31

Just use the length of sys.argv

if len(sys.argv) == 2:
  # do X
else:
  # do Y
varunl
  • 19,499
  • 5
  • 29
  • 47
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.

Leovt
  • 313
  • 2
  • 4
3

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.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
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
Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
  • But no way to specifically pull the value in eur_hedge without throwing up a need more/too many variable to unpack argument? – Felix Feb 25 '12 at 07:58
  • 2
    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. – Lukáš Lalinský Feb 25 '12 at 08:00
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
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

JCE2423
  • 19
  • 5