Unexpected (by me) exec behavior

Discussion in 'Python' started by Mark Wright, Jul 8, 2003.

  1. Mark Wright

    Mark Wright Guest

    I have a script that I use to control our build process. It is a
    general purpose script that exec's other scripts that contain project
    specific python code. In one of those other, project-specific,
    scripts I exec a third script. That third script is failing because
    it can't seem to 'import' successfully. It seems that if one 'exec's
    a string that in turn 'exec's another string, the 'import's don't work
    in the second string. I'm assuming that I'm misunderstanding
    something about Python namespaces, but here's an example that
    illustrates the problem:

    ----------------------------
    # filename = t.py
    s1 = """
    s2 = \"\"\"
    import socket
    def xyz():
    print socket.gethostbyname('somehost')
    if __name__ == '__main__':
    xyz()
    \"\"\"

    def abc():
    exec s2
    if __name__ == '__main__':
    abc()
    """

    exec s1
    -----------------------------

    Traceback (most recent call last):
    File "t.py", line 24, in ?
    exec s1
    File "<string>", line 13, in ?
    File "<string>", line 11, in abc
    File "<string>", line 6, in ?
    File "<string>", line 4, in xyz
    NameError: global name 'socket' is not defined

    Can anyone explain this to me?

    Mark
     
    Mark Wright, Jul 8, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hal Vaughan
    Replies:
    11
    Views:
    1,198
    Gordon Beaton
    May 22, 2006
  2. tedsuzman
    Replies:
    2
    Views:
    7,167
    Michel Claveau, résurectionné d'outre-bombe inform
    Jul 21, 2004
  3. Ted
    Replies:
    1
    Views:
    497
    Duncan Booth
    Jul 22, 2004
  4. Guillermo Riojas
    Replies:
    0
    Views:
    200
    Guillermo Riojas
    Nov 26, 2010
  5. Random Task
    Replies:
    12
    Views:
    733
    Joe Smith
    Dec 4, 2005
Loading...

Share This Page