Ritz
Ritz

Reputation: 1253

argparse not taking default option

Can anyone tell me why the default option is being taken below?

Code:

import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL loading by default..',required=False)
global force_edl
results = parser.parse_args()

if results.force_edl:
    force_edl = results.force_edl
print "force_edl"
print force_edl

Error message:

Traceback (most recent call last):

File "defaultparse.py", line 10, in

print force_edl

NameError: global name 'force_edl' is not defined

Upvotes: 0

Views: 293

Answers (3)

kmario23
kmario23

Reputation: 61365

results.force_edl will always be False. You're updating the global variable after conditional checking, which will never be executed. And the global force_edl will still be undefined since you didn't assign any value to it when you declared.

Do something like the following:

global force_edl = False

Upvotes: 0

cafebabe1991
cafebabe1991

Reputation: 5176

The error occurred because the variable force_edl was just "DECLARED" but not "DEFINED" with some value.

It gets assigned in your if block only but that if block won't execute since the value by default will be a false value and hence you get this error.

You must assign it some value before you use it.

Upvotes: 0

Nehal J Wani
Nehal J Wani

Reputation: 16619

if results.force_edl:
    force_edl = results.force_edl

The reason why the assignment inside the above if doesn't take place is because:

>>> results
Namespace(force_edl=False)
>>> results.force_edl
False

results.force_edl is a boolean with the value False. What you instead need to be doing is:

if 'force_edl' in results:
    force_edl = results.force_edl

Or, since you already know that results will always have force_dl, just assign directly:

force_edl = results.force_edl

Upvotes: 2

Related Questions