how to access global variable within __main__ scope?
Question: I'm confused about the namespace and scope of variables in python

Suppose I have a test.py:

    
    
    # -*- coding: utf-8 -*-
    """
    @author: jason
    """
    
    if __name__ == '__main__':
        global strName
        print strName
    

and then, I define a variable named strName and try to access it in the
test.py, but it throws an error:

    
    
    In [9]: strName = "Joe"
    
    In [10]: run test.py hello
    ---------------------------------------------------------------------------  NameError                              Traceback (most recent call last)  C:\Anaconda\lib\site-packages\IPython\utils\py3compat.pyc in execfile(fname, glob, loc)
        195             else:
        196                 filename = fname
    --> 197             exec compile(scripttext, filename, 'exec') in glob, loc
        198     else:
        199         def execfile(fname, *where):
    
    d:\playground\test.py in <module>()
         13         print "hello"
         14         global strName
    ---> 15         print strName
         16 
    
    NameError: global name 'strName' is not defined
    
    In [11]:
    

I was wondering why this happens and is there any way to access strName in
test.py?


Answer: **test.py:**

    
    
    strName = "John Doe"
    print strName
    

**Interactive Shell:**

    
    
    $ python
    >>> from test import strName
    >>> print strName
    John Doe
    

