[Tutor] eval use (directly by interpreter vs with in a script)

Alex Kleider akleider at sonic.net
Sun Nov 2 21:01:26 CET 2014


I'm puzzled by the following behaviour:

The following works as I expect:

alex at x301:~/Python$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:18)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> code = """\
... s1 = 'first'
... s2 = 'second'
... """
>>> exec(code)
>>> s1
'first'
>>> s2
'second'
>>> 

..the following script also behaves as I expect:
alex at x301:~/Python$ cat test.py
#!/usr/bin/env python3
"""
Testing use of exec().
"""
code = """\
s1 = 'first'
s2 = 'second'
"""
exec(code)
print(s1)
print(s2)
alex at x301:~/Python$ ./test.py
first
second

... but this one doesn't:
alex at x301:~/Python$ cat t1.py
#!/usr/bin/env python3
"""
Testing use of exec().
"""
code = """\
s1 = 'first'
s2 = 'second'
"""

def main():
     exec(code)
     print(s1)

if __name__ == "__main__":
     main()
alex at x301:~/Python$ ./t1.py
Traceback (most recent call last):
   File "./t1.py", line 15, in <module>
     main()
   File "./t1.py", line 12, in main
     print(s1)
NameError: name 's1' is not defined

Any light that can be shed onto this would be appreciated.
Alex



More information about the Tutor mailing list