Unexpected (by me) exec behavior

Mark Wright mwright at pro-ns.net
Tue Jul 8 17:18:06 CEST 2003


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




More information about the Python-list mailing list