Search code examples
pythonglobal-variablesgetopt

NameError: global name 'b' is not defined


I have an script wih the following structure:

def func():
    bfile=open(b, 'r')
    cfile=open(c, 'r')
    dfile=open(d, 'r')

if __name__=='__main__':
    if len(sys.argv)==1:
        print 'guidence'
        sys.exit()
    else:
        opts,args=getopt.getopt(sys.argv,'b:c:d:a')
        a=False
        for opt,arg in opts:
            if opt=='-a':
                a=True
            elif opt=='-b':
                b=arg
            elif opt=='-c':
                c=arg
            elif opt=='-d':
                d=arg
        func()

I run it in this way:

# python script.py -b file1 -c file1 -d file1

in func()
NameError: global name 'b' is not defined

I also define a global file1. but no work.

Update

I know where the problem is: the result of print opts is []. It has not values. why?


Solution

  • You have two issues.

    First, getopt stops if it encounters a non-option. Since sys.argv[0] is the script name, it's a non-option and the parsing stops there.
    You want to pass sys.argv[1:] to getopt.

    This is what's causing print opts to show [], and since opts is empty the global variables are never created, which is where the complaint that they don't exist come from.

    Second, since -a wants a parameter, you need a colon after it.

    In all, this should work:

    opts, args = getopt.getopt(sys.argv[1:], 'b:c:d:a:')
    

    Also, you shouldn't pass parameters in globals.