python - NameError: global name 'b' is not defined -
i have script wih 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 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 in way:
# python script.py -b file1 -c file1 -d file1 in func() nameerror: global name 'b' not defined i define global file1. no work.
update
i know problem is: result of print opts []. has not values. why?
you have 2 issues.
first, getopt stops if encounters non-option. since sys.argv[0] script name, it's non-option , parsing stops there.
want pass sys.argv[1:] getopt.
this what's causing print opts show [], , since opts empty global variables never created, complaint don't exist come from.
second, since -a wants parameter, need colon after it.
in all, should work:
opts, args = getopt.getopt(sys.argv[1:], 'b:c:d:a:') also, shouldn't pass parameters in globals.
Comments
Post a Comment