0

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?

Community
  • 1
  • 1
MLSC
  • 5,872
  • 8
  • 55
  • 89

2 Answers2

0

You have to pass the filenames to the function. In Your case it should look like this:

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

You can call it with:

b = 'nameB.txt'
c = 'nameC.txt'
d = 'nameD.txt'
func(b, c, d)
Dzarafata
  • 558
  • 3
  • 11
0

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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82