首页 > 解决方案 > 如何将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) 时,它可以工作。

有没有办法将其存储为变量以及导致问题的原因?我不明白出了什么问题。

标签: python

解决方案


shell.command在被调用之前不会被定义shell.__init__,但是直到 afterbasic被导入才会发生。但是为了执行basic.py以完成导入,您需要shell.command进行定义。

您应该重新设计您的模块,这样shell.pybasic.py不必导入main.


推荐阅读