首页 > 解决方案 > python -m 导致“查找模块规范时出错”

问题描述

医生

一些 Python 模块也可用作脚本。这些可以使用 python -m module [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__')

是什么导致了这个错误?如何解决?

标签: python

解决方案


您应该使用不带 .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 参数是一个模块,类似于importor from


推荐阅读