许多python包包括命令行工具。这对于分发和包相关联的支持工具是很有的。
为了“funniest”,我们添加一个“funniest-joke”命令行工具。
setuptools.setup()提供了两种机制去实现:
- 通过scripts关键字
- 通过entry_points的console_scripts
用scripts关键字
这种方法是在一个单独的文件里写你的脚本。例如
funniest/
funniest/
__init__.py
...
setup.py
bin/
funniest-joke
...
这funniest-joke脚本如下
#!/usr/bin/env python
import funniest
print funniest.joke()
定义在setup()如下
setup(
...
scripts=['bin/funniest-joke'],
...
)
当我们安装包,setuptools会将脚本拷贝到PATH, 可我们可以直接如下调用
$ funniest-joke
这个好处是工具脚本可以是python也可以不是python。
This has advantage of being generalizeable to non-python scripts, as well: funniest-joke
could be a shell script, or something completely different.
console_scripts 入口
第二个方法就是使用‘entry point’。Setuptools允许模块去注册entrypoints,也提供了自己的例如console_scripts entry point.
其允许Python函数直接注册为命令行可执行工具。在这种情况下,我们需要添加一个新文件和功能去支持它。
如下:
funniest/
funniest/
__init__.py
command_line.py
...
setup.py
...
In this case, we’ll add a new file and function to support the command line tool:
command_line.py内容如下:
import funniest
def main():
print funniest.joke()
我们可以直接测试这个脚本,如下:
$ python
>>> import funniest.command_line
>>> funniest.command_line.main()
...
我们可以在setup.py中注册main()函数,如下:
setup(
...
entry_points = {
'console_scripts': ['funniest-joke=funniest.command_line:main'],
}
...
)
当这个包被安装后,我们可以在命令行直接运行‘funniest-joke’。Setuptools会直接生成一个独立的脚本,导入了你的模块和注册的函数。
这种方法的优势是非常方便进行测试。不用在shell端去触发执行脚本,我们就可以有如下测试代码:
from unittest import TestCase
from funniest.command_line import main
class TestConsole(TestCase):
def test_basic(self):
main()
为了让其更有用,我们会需要一个捕捉标准输出的context manager, 但其不在该文讨论范围。