Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 导入模块在生成uu pycache uuu后停止工作_Python 3.x - Fatal编程技术网

Python 3.x 导入模块在生成uu pycache uuu后停止工作

Python 3.x 导入模块在生成uu pycache uuu后停止工作,python-3.x,Python 3.x,我正在动态导入模块 在我的主文件中,在项目根目录中 sys.path.append(os.path.join(os.path.dirname(__file__), "mylib")) 在我的命令导入文件中,mylib/nogui/main.py commands_path = Path(__file__).parent.joinpath("command") for dirpath, dirnames, filenames in walk(command

我正在动态导入模块

在我的主文件中,在项目根目录中

sys.path.append(os.path.join(os.path.dirname(__file__), "mylib"))
在我的命令导入文件中,
mylib/nogui/main.py

commands_path = Path(__file__).parent.joinpath("command")
for dirpath, dirnames, filenames in walk(commands_path):
    for file in filenames:
        if file.startswith("cmd_"):
            imported_module = import_module(f"mylib.nogui.command.{file[:file.find('.py')]}")
            imported_module.register()
mylib.nogui.command
目录中是文件
cmd_echo.py

def register():
    print("This works")
如果我第一次运行主文件,我会看到:

This works
如果我再次运行它,我会看到:

ModuleNotFoundError:没有名为“mylib.nogui.command.cmd_echo.cpython-37”的模块mylib.nogui.command.cmd_echo'不是一个包


唯一的区别是存在_upycache__;文件夹。如果我删除此文件夹,它会再次正常工作。

答案是
os。默认情况下,walk
是递归的

“This works”仍在输出中,但被错误消息隐藏。我的错误

目标模块(cmd_echo)正在导入,但随后
os.walk
进入了_pycache__;文件夹并在那里运行了动态导入代码,这导致了此错误。简单的解决方案是在第一个循环后添加一个中断

commands_path = Path(__file__).parent.joinpath("command")
for dirpath, dirnames, filenames in walk(commands_path):
    for file in filenames:
        if file.startswith("cmd_"):
            imported_module = import_module(f"rantlib.nogui.command.{file[:file.find('.py')]}")
            imported_module.register()
    break

答案是
os。默认情况下,walk
是递归的

“This works”仍在输出中,但被错误消息隐藏。我的错误

目标模块(cmd_echo)正在导入,但随后
os.walk
进入了_pycache__;文件夹并在那里运行了动态导入代码,这导致了此错误。简单的解决方案是在第一个循环后添加一个中断

commands_path = Path(__file__).parent.joinpath("command")
for dirpath, dirnames, filenames in walk(commands_path):
    for file in filenames:
        if file.startswith("cmd_"):
            imported_module = import_module(f"rantlib.nogui.command.{file[:file.find('.py')]}")
            imported_module.register()
    break