Unexpected (by me) exec behavior

M

Mark Wright

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top