将已安装的Python包作为脚本执行?

2024-04-26 01:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以将包作为脚本执行?例如:

[~]# easy_install /path/to/foo.egg
...
[~]# python -m foo --name World
Hello World

我试图在包中创建一个__main__.py文件,但它没有被执行(我使用的是Python 2.6)。出现以下错误:

foo is a package and cannot be directly executed

我的包裹结构如下:

foo/
  setup.py
  foo/
    __init__.py
    __main__.py

运行python -m foo.__main__ --name World如预期的那样工作,但我更喜欢前一种执行方式。这可能吗?


Tags: install文件topath方法namepy脚本
3条回答

我认为这可能是Python2.6的一个限制。我已经测试过了,使用-m选项执行一个包(在.中或从一个带有easy_install的egg中安装)在2.7中可以正常工作,但在2.6中不行。例如,在我的系统(Ubuntu)上,当前目录中有一个名为pkg_exec的测试包,其中__main__.py只打印sys.argv

xx@xx:~/tmp/pkg_exec$ python2.6 -m pkg_exec
/usr/bin/python2.6: pkg_exec is a package and cannot be directly executed
xx@xx:~/tmp/pkg_exec$ python2.7 -m pkg_exec
['/home/xx/tmp/pkg_exec/pkg_exec/__main__.py']

另外,根据the 2.7 docs

Changed in version 2.7: Supply the package name to run a __main__ submodule.

只要包在python路径上, 在脚本末尾添加。

if __name__ == "__main__":
     call_script()
$ python -m module_name  

将运行模块,例如

python -m random

这是Python2.6中的回归。见issue2571

The ability to execute packages was never intended, since doing so breaks imports in a variety of subtle ways. It was actually a bug in 2.5 that it was permitted at all, so 2.6 not only disabled it again, but also added a test to make sure it stays disabled (2.4 correctly rejected it with an ImportError, just as 2.6 does).

您有几个选项,可以始终指定main来运行它:

$ python -m module.__main__

或者可以编写一个shell脚本包装器来检测python版本,然后以不同的样式执行它。

或者,您可以在命令行上执行代码,该命令行将导入并运行模块,然后可能将其放入shell脚本中:

$ python -c "import module; module.main()"

在我自己的命令行项目中,我既有捕获错误(未安装python等)的shell脚本,也有执行导入代码并检测是否安装了必要的模块并提示错误(带有有用的链接或安装文本)。

相关问题 更多 >