2017-12-01 12 views
1

これは動作します:Pythonの幹部は、モジュールの動作中に実行されているが、機能ではない

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

そして、これはない:

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

run() 

結果:

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 

誰もが私の理由と方法を教えてもらえをそれを修正するには?

答えて

1

私は再び読んだ - carrefully - python's docs特に、このいずれかを:

モジュールレベルで、グローバルと地元の人々が

同じ辞書であり、これを試していることを忘れないでください:

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

run() 

これは現在機能しています!

私はまだなぜそれが動作するのかまだ分かりませんが、

関連する問題