1

This works:

import os
import sys
with open('tests.py') as fptr:
    script_content = fptr.read()
exec(script_content)

And this not:

def run():
    import os
    import sys
    with open('tests.py') as fptr:
        script_content = fptr.read()
    exec(script_content)

run()

Result:

Traceback (most recent call last):
  File "tmp.py", line 8, in <module>
    run()
  File "tmp.py", line 6, in run
    exec(script_content)
  File "<string>", line 15, in <module>
  File "<string>", line 16, in PlaceSpitter
NameError: name 'Place' is not defined

Could anyone tell my why and how to fix it?

1 Answer 1

1

I've read again - carrefully - python's docs especially this one:

Remember that at module level, globals and locals are the same dictionary

And try this:

def run():
    import os
    import sys
    with open('tests.py') as fptr:
        script_content = fptr.read()
    exec(script_content, globals())

run()

which now works!

I still don't know why but now at least it works.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.