假设某处有一个模块,我可以用它导入
from sound.effects import echo
如何直接从命令行运行 echo?
命令
python sound/effects/echo.py
不起作用,因为相对路径通常不正确
请您参考如下方法:
如果模块在导入时执行了顶层代码,您可以使用 -m switch从命令行运行它(使用 Python 属性表示法):
python -m sound.effect.echo
模块随后作为脚本执行,因此 if __name__ == '__main__': 守卫将通过。参见例如 timeit module ,它在像这样从命令行运行时执行 timeit.main() 函数。
