Kalyan
Kalyan

Reputation: 119

Python NameError global name is not defined - variable does not find its value in Thread

I am struck at one point in my python code. I am trying to call a thread class object in my class to show a loading bar while my actual function fetches the values. I have 2 class files progress.py which has the loading code and my gmond_class.py which has the actual function which fetch the values. I am confused with the error global variable 'stop' is not defined in my thread class file when the code reaches to evaluate the stop variable not equal to True.can anyone please help me. Please check my code class file gmond_class file.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
import sys
import time
import subprocess
import prettytable
from progress import *
global kill
global stop
p = progress_bar_loading()

class gmond_class:

   chkMinionUp      = ''
   chkMinionUpRes   = ''
   chkMinionDown    = ''
   chkMinionDownRes = ''
   gmondChkMinion   = ''
   gmondMinionRes   = ''
   replaceHyfen     = ''
   splitStr         = ''
   verifyService    = ''
   chkMinionOut     = ''
   minion           = ''
   checkError       = ''
   checkService     = ''
   checkGm          = ''
   onchange         = ''
   gmd              = ''
   final            = ''
   code             = ''
   cmdMinion        = ''
   removeItem       = ''
   max_value        = 10
   alive            = ''

   def displayMinionUp(self):
       self.kill = False
       self.stop = False
       print type(self.kill)
       p.start()
       try:
           self.alive = self.getMinionUp()
           if self.alive !='':
              time.sleep(1)
              self.stop = True
       except KeyboardInterrupt or EOFError:
           kill = True
           stop = True

   def getMinionUp(self):
       self.chkMinionUp    = subprocess.Popen("salt-run manage.up | wc -l", shell = True, stdout=subprocess.PIPE)
       self.chkMinionUpRes = self.chkMinionUp.communicate()[0].rstrip()
       if len(self.chkMinionUpRes) > 0:
          self.printBlank()
          return str(self.chkMinionUpRes)
       else:
          return 0


class file progress.py

#!/usr/bin/python

import sys
import time
import threading

class progress_bar_loading(threading.Thread):

    def run(self):
        global stop
        global kill
        print 'Loading....  ',
        sys.stdout.flush()
        i = 0
        while stop != True:
            if (i%4) == 0:
               sys.stdout.write('\b/')
            elif (i%4) == 1:
                 sys.stdout.write('\b-')
            elif (i%4) == 2:
                 sys.stdout.write('\b\\')
            elif (i%4) == 3:
                 sys.stdout.write('\b|')

                 sys.stdout.flush()
                 time.sleep(0.2)
                 i+=1

        if kill == True:
           print '\b\b\b\b ABORT!',
        else:
           print '\b\b done!',


Error Message :

[root@vmsalt-master test]# python check_gmond_config.py 

<type 'bool'>
Loading....  Exception in thread Thread-1:
Traceback (most recent call last):File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner self.run()
File "/root/python-salt/test/progress.py", line 14, in run while stop != True:
NameError: global name 'stop' is not defined

Upvotes: 0

Views: 1680

Answers (1)

skyking
skyking

Reputation: 14395

That's because you haven't actually defined stop. Just saying global stop doesn't do that - it only says that stop should be looked up in the global scope instead of local (anyway).

To actually define stop you have to assign a value to it, for example stop = None. The only place this happens is when KeyboardInterrupt or EOFError has been catched (the assignment stop = True).

Also there seem to be some confusion on how attribute references work. Attribute references means lookup in several stages. For example self.stop means to first lookup self in the normal way and once the object is found the stop attribute is looked up inside that object. Now self is in this case passed as a parameter to the function which makes self a local variable. The global/local status only applies to the first step in this lookup.

Upvotes: 2

Related Questions