我无法在变量中存储全局变量

我有3个python文件:

main.py

import shell
import basic

if __name__ == "__main__":
    shell.init()

shell.py

import main

def init():
    while True:
        global command
        command = input("")
        main.basic.interpreter()

if __name__ == "__main__":
    init()

和basic.py

import main

com = main.shell.command

def interpreter():
    return com

When I run main.py it runs shell.py which asks for user input and then stores it in a global variable and calls the interpreter function that returns the com varibale. But when I run it I get an error: module 'shell' has no attribute 'command', and when I tested it again I got: partially initialized module 'shell' has no attribute 'command' (most likely due to a circular import).

but when I remove the com variable and instead returning the main.shell.command (return main.shell.command) it works.

有没有办法将其存储为变量,是什么引起了问题? 我不明白怎么了

评论
FBI
FBI

shell.command doesn't get defined until shell.__init__ gets called, but that doesn't happen until after basic is imported. But in order to execute basic.py in order to complete the import, you need shell.command to be defined.

You should redesign your modules so that shell.py and basic.py don't have to import main.

点赞
评论