Python: Command Line Scripts

许多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, 但其不在该文讨论范围。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值