Python 无限期导入.py文件

Python 无限期导入.py文件,python,Python,我是python的新手,我想尝试从一个文件移动到另一个文件,比如无限期地在fileA和fileB之间循环。但是,当我尝试使用导入功能时,文件只相互导入一次,然后停止。有没有办法多次导入整个文件 文件A: story1 = "You see a statue of a metal man peeking out of a building. A park is just across the street.\n\nPossible exits: north." map_legend = "\nMa

我是python的新手,我想尝试从一个文件移动到另一个文件,比如无限期地在fileA和fileB之间循环。但是,当我尝试使用导入功能时,文件只相互导入一次,然后停止。有没有办法多次导入整个文件

文件A:

story1 = "You see a statue of a metal man peeking out of a building. A park is just across the street.\n\nPossible exits: north."
map_legend = "\nMap Legend:\nG   you\n.   clear path\n-|  wall\n+   door\n"
map1 = "-.\n |G\n-//\n|.|\n---"

while True:
    print(story1)
    action = input(str())
    while action != 'north':
            print ('there is nothing there.')
            action = input(str())
    ***import story2***
    continue
文件B:

story2 = "You see a map on the bench. Type 'grab' to pick it up.\n\nPossible exits: north and south."
map_legend = "\nMap Legend:\nG   you\n.   clear path\n-|  wall\n+   door\n"
map1 = "-.\n |G\n-//\n|.|\n---"
inventory=list()
action = 'north'

while True:
    print(map_legend,"\n",map1,"\n")
    direction = f"you moved {action}."
    print(direction)
    print(story2)
    action = input(str())
    while action != 'north' and action != 'south' and action != 'grab':
        print ('there is nothing there.')
        action = input(str())
    if action == 'grab':
        inventory.append('1 map')
        print ("Inventory:\n1 map")
        action = input(str())
    while action != 'north' and action != 'south':
        print ('there is nothing there.')
        action = input(str())
    if action == 'south':
        direction = f"you moved {action}."
        print(direction)
        ***import story1***
        continue
所以,从fileA移到fileB没有问题,但是在从fileB移到fileA之后,我不能再“导入”fileB了。这里的“导入”功能是否使用错误


谢谢。

每个文件都应该定义一个函数(使用
def
关键字),而不是直接在
.py
文件中编写代码。然后,您可以
从这些文件导入
函数,并在循环中一个接一个地调用它们


也就是说,如果您真的想重新导入模块(而不是重复使用现有的模块对象,
import
语句就是这样做的),您可以使用。

而不是直接在
.py
文件中写入代码,每个文件都应该定义一个函数(使用
def
关键字)。然后,您可以
从这些文件导入
函数,并在循环中一个接一个地调用它们


也就是说,如果您真的想重新导入模块(而不是重复使用现有的模块对象,
import
语句就是这样做的),那么您可以使用。

解决方案是将要重新使用的代码放入其中,然后您可以重复调用函数来执行您想要的操作

例如:

A.py

B.py


解决方案是将要重用的代码放入其中,然后可以重复调用函数来执行所需操作

例如:

A.py

B.py


在文件a和文件B中定义函数。使用这些文件及其函数在模块中导入,并创建一个相互调用的循环。但是,这不是一个好方法。

在fileA和fileB中定义函数。使用这些文件及其函数在模块中导入,并创建一个相互调用的循环。但是,这不是一个好办法。

尽管这不是你问题的答案,但我坚信不断循环导入两个文件并不是制作应用程序的最佳逻辑。如果你想使用另一个文件中的代码,最好在这个文件中创建一些函数,并在需要时使用它们。尽管这不是你问题的答案,但我坚信,不断循环导入两个文件并不是制作应用程序的最佳逻辑。如果您想使用另一个文件中的代码,最好在此文件中生成一些函数,并在需要时使用它们。
def do_thing():
    # some code

def do_other_thing():
    # more code
import A

while True:
    A.do_thing()
    A.do_other_thing()