gpt4 book ai didi

python -m 导致 "Error while finding module specification for"

转载 作者:行者123 更新时间:2023-12-01 00:35:50 25 4
gpt4 key购买 nike

文档 says

Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file for module as if you had spelled out its full name on the command line

我编写这段代码是为了帮助自己理解-m

def print_hi(n=1):
print('hi'*n)

if __name__ == "__main__":
print_hi(9)

我将其保存为文件aname.py

然后我运行了这个命令,并得到了预期的结果。

$ python aname.py 
hihihihihihihihihi

问题

当我将文件作为模块执行时,会出现此错误

$ python -m aname.py
/usr/bin/python: Error while finding module specification for 'aname.py' (AttributeError: module 'aname' has no attribute '__path__')

什么原因导致此错误?如何解决?

最佳答案

您应该使用不带 .py 后缀的 m,即:$ python -m aname

来自手册页:

       -m module-name
Searches sys.path for the named module and runs the corresponding .py file as
a script.

m 参数是一个模块,类似于 importfrom

关于python -m 导致 "Error while finding module specification for",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com