多次从文件运行python文件

时间:2016-12-14 14:51:42

标签: python list class pygame instance

基本上我正在制作塔防游戏,我有一个名为enemy.py的python文件,里面有圆形,我有一个名为main.py的文件,它是圆形屏幕的结尾。我希望main.py在每一轮完成后执行enemy.py,但它第二次给我一个错误。我正在使用导入功能打开其他文件。另外有人可以帮助我这么做,所以错误不是那么大我很困惑!

Traceback (most recent call last):
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 62, in <module>
    createMenu()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 9, in     createMenu
    newRound()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 23, in     newRound
    cancelLoop()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 38, in     cancelLoop
    startRound()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 41, in     startRound
    import enemy.py
  File "H:\ICT\A level\Computing\Tower Defense Code\enemy.py", line 107, in     <module>
    enemy.draw(screen)
  File "H:\ICT\A level\Computing\Tower Defense Code\enemy.py", line 35, in     draw
    life(self)
  File "H:\ICT\A level\Computing\Tower Defense Code\enemy.py", line 55, in     life
    import main.py
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 62, in     <module>
    createMenu()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 9, in     createMenu
    newRound()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 23, in     newRound
    cancelLoop()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 38, in     cancelLoop
    startRound()
  File "H:\ICT\A level\Computing\Tower Defense Code\main.py", line 41, in    startRound
    import enemy.py
ImportError: No module named 'enemy.py'; 'enemy' is not a package
  
    
      

    
  

1 个答案:

答案 0 :(得分:4)

首先删除.py文件后缀。语法只是:

import enemy

这将运行enemy.py中的所有代码(假设enemy.py位于Python已知的路径中)。

如果您想重复此过程,请使用的命令是:

reload(enemy)

这不是使用模块的好方法。你最好在敌人内部创建一个函数并直接调用它:

import enemy
enemy.enemy()