Cmag Cmag - 1 month ago 5
Python Question

Checking if sys.argv[x] is defined

What would be the best way to check if a variable was passed along for the script:

try:
sys.argv[1]
except NameError:
startingpoint = 'blah'
else:
startingpoint = sys.argv[1]

Answer

In the end, the difference between try, except and testing len(sys.argv) isn't all that significant. They're both a bit hackish compared to argparse.


This occurs to me, though -- what do people think of this, as a sort of low-budget argparse?

arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))

You could even use it to generate a namedtuple with values that default to None!

Arg_list = collections.namedtuple('Arg_list', arg_names)
args = Arg_list(*(args.get(arg, None) for arg in arg_names))

And all in just four lines.

Comments