跳转到主要内容

用于将monkeypatches应用到Python可执行文件的工具。

项目描述

Build Status Coverage Status

pymonkey

用于将monkeypatches应用到Python可执行文件的工具。

安装

pip install pymonkey

注册补丁

创建模块

## mymod/pymonkey.py

# Be sure to not import anything at the module scope
# This ensures that import-hook patching will work better later


# This is your chance to do argument parsing before running the target
# executable.
# This will be called after all of the patch hooks have been registered.
def pymonkey_argparse(argv):
    # You'll be passed the arguments as a tuple.  Parse your specific arguments
    # and return your parsed state and the remaining arguments.
    # If you wish to forgo argparsing, simply `return None, argv`
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo')
    return parser.parse_known_args(argv)


# This is your entry point.  It will be passed module objects after they have
# been imported.  Check the module name and then apply your patch (if
# applicable).
# This will be called as a post-import hook so you'll have a chance to modify
# the module before another module would import from it.
# The parsed state computed above will be passed as `args`
def pymonkey_patch(mod, args):
    # This callback will be called with *every* module that gets imported
    # Guard against the specific module you'd like to patch
    if mod.__name__ != 'module_to_patch':
        return

    # Apply your patches here to module_to_patch
    mod.foo = args.foo

并将条目添加到setup.py中

setup(
    ...,
    entry_points={
        'pymonkey': ['mymod = mymod.pymonkey:pymonkey_patch'],
        'pymonkey.argparse': ['mymod = mymod.pymonkey:pymonkey_argparse'],
    },
    ...
)

命令行用法

应用单个补丁

$ pymonkey mymod -- pip install simplejson

应用所有可用的补丁

$ pymonkey --all -- pip install simplejson

查看帮助

$ pymonkey --help

使用pymonkey创建条目

在模块中

## mymod_main.py
from pymonkey import make_entry_point

# The first argument is a list of pymonkey patches to apply
# The second argument is the entry point to run
main = make_entry_point(('mymod',), 'pip')

if __name__ == '__main__':
    exit(main())

在setup.py中

setup(
    ...,
    entry_points={
        'console_scripts': ['pip-patched = mymod_main:main'],
        'pymonkey': ['mymod = mymod.pymonkey:pymonkey_patch'],
        'pymonkey.argparse': ['mymod = mymod.pymonkey:pymonkey_argparse'],
    },
    ...
)

然后,而不是

$ pymonkey mymod -- pip ...

您现在可以这样做

$ pip-patched ...

使用pymonkey进行的事情

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定要选择哪个,请了解更多关于安装包的信息。

源代码分发

pymonkey-0.3.1.tar.gz (6.1 kB 查看哈希)

上传时间: 源代码

构建分发

pymonkey-0.3.1-py2.py3-none-any.whl (6.5 kB 查看哈希值)

上传时间 Python 2 Python 3