Python 3:使用exec(打开("路径")。read())打开文件并从文件运行代码

时间:2017-05-15 16:35:40

标签: python-3.x

我正在Moment写一篇小游戏来学习Python 3,我想通过使用exec()获取文件并执行脚本来导入另一个游戏:

运行此脚本时: http://paste.ubuntu.com/24581759/

我想将此脚本用作游戏中的游戏: http://paste.ubuntu.com/24581775/

获取文件并运行脚本的部分:

class Kitchen(Thing):

    def enter(self):
        print(dedent("""
            you in kitchen.
            """))

        action = input("> ")

        if action == "use pc":
            exec(open("//home/opusa/probes/ex35.py").read())
            return 'kitchen'

        if action == "make sandwitch":
            print(dedent("""
                you made sandwitch. now way better.
                """))
            return 'the_end'

        else:
            print(dedent("make sandwitch"))
            return 'kitchen'

我明白了:

Traceback (most recent call last):
  File "mygame.py", line 115, in <module>
    a_game.play()
  File "mygame.py", line 29, in play
    next_thing_name = current_thing.enter()
  File "mygame.py", line 75, in enter
    exec(open("//home/opusa/probes/ex35.py").read())
  File "<string>", line 77, in <module>
  File "<string>", line 70, in start
NameError: name 'bear_room' is not defined

如果我使用其他脚本,一切正常......

请指出我的错误以及我可以在哪里阅读。到目前为止找不到任何有用的东西。 谢谢!

0 个答案:

没有答案