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



文档说

一些 Python 模块作为脚本也很有用。这些可以使用python -m模块[arg] ...调用,它执行模块的源文件,就好像你在命令行上拼写了它的全名一样。

我写这段代码是为了帮助自己理解-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

最新更新