【问题标题】:when i import module it runs the whole python file当我导入模块时,它运行整个 python 文件
【发布时间】:2019-08-06 23:49:36
【问题描述】:

client.py

# Importing modules
import os
import asyncio
import sys
import Events
import glob
import Plugins
global FPath
global PlugPath
global CMDPath
FPath = os.path.dirname(os.path.abspath(__file__))
PlugPath = os.path.dirname(os.path.abspath(__file__)) + "\\Plugins"

Events.Startup()
global cmds
cmds = input("\\>")
global commandlst
commandlst = cmds.split()
command = commandlst[0]
runpy = "python " + str(FPath) + "\\" +  str(command) + ".py"
if(os.path.isfile(FPath + "\\" + command + ".py") == True):
    os.system(runpy)
else:
    print(command + " is not a command or a plugin command!")
    os.system("ping localhost -n 2 >nul")
    os.system("py client.py")

help.py

import json
from pprint import pprint
import os
import sys
import client
commands = json.loads(open(sys.path[0] + "\\commands.json").read())

当它导入客户端时,它会运行整个 client.py 文件。 我已经尝试从客户端导入 commandlst 并且没有任何效果。 请帮忙。

【问题讨论】:

  • Python import mechanics的可能重复
  • 这就是 Python 的工作原理。当您在 Python 中导入模块时,它会执行该代码中的所有内容。如果您不想执行某些部分代码,则应将其写入 if __name__ == '__main__': 范围内。

标签: python python-import


【解决方案1】:

这就是导入的工作方式。要解决您的特定问题 - 不要运行整个 client.py 模块,您可以将其内容放入 if __name__ == '__main__': 检查如下:

# Importing modules
...
if __name__ == '__main__':
    global FPath
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-14
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2017-11-14
    • 1970-01-01
    相关资源
    最近更新 更多