首页 > 解决方案 > 当我导入模块时,它运行整个 python 文件

问题描述

客户端.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")

帮助.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 并且没有任何效果。请帮忙。

标签: pythonpython-import

解决方案


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

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

推荐阅读