python - 如何将2个文件相互导入
问题描述
我有 3 个 python 文件:
主文件
import shell
import basic
if __name__ == "__main__":
shell.init()
外壳.py
import main
def init():
while True:
global command
command = input("")
main.basic.interpreter()
if __name__ == "__main__":
init()
和基本的.py
import main
com = main.shell.command
def interpreter():
return com
当我运行main.py
它时,shell.py
它会要求用户输入,然后将其存储在全局变量中并调用interpreter
返回变量的函数com
。但是当我运行它时,我得到一个错误:
module 'shell' has no attribute 'command'
,当我再次测试它时,我得到:partially initialized module 'shell' has no attribute 'command' (most likely due to a circular import)
。
但是当我删除com
变量并返回main.shell.command
( return main.shell.command
) 时,它可以工作。
有没有办法将其存储为变量以及导致问题的原因?我不明白出了什么问题。
解决方案
shell.command
在被调用之前不会被定义shell.__init__
,但是直到 afterbasic
被导入才会发生。但是为了执行basic.py
以完成导入,您需要shell.command
进行定义。
您应该重新设计您的模块,这样shell.py
就basic.py
不必导入main
.
推荐阅读
- python-3.x - 当列值满足特定条件时,在 panda 数据帧的行中提取 2 列数据
- javascript - 对象未按预期呈现
- ms-access - 带有格式化自动编号的 MS Access 自定义参考 ID 字段
- python - 在一行 Python 中无法使用 if/else
- wordpress - WooCommerce 产品变体未显示,而这些在数据库中
- bash - 使用 sed 更改值,使用两个变量,多个值用空格分隔
- c# - Razor Pages Web App (.Net core 2.1) - 如何处理从一个区域页面到另一个区域页面的重定向
- reactjs - Firebase 身份验证和反应
- c++ - 按字符读取 PDF 文件的内容
- javascript - 将数据从 MATLAB 发送到本地网站