Unexpected (by me) exec behavior

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark Wright

    Unexpected (by me) exec behavior

    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 misunderstandin g
    something about Python namespaces, but here's an example that
    illustrates the problem:

    ----------------------------
    # filename = t.py
    s1 = """
    s2 = \"\"\"
    import socket
    def xyz():
    print socket.gethostb yname('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
Working...