python - 自动执行模块方法前面的代码

标签 python python-requests

我正在使用 requests模块,但问题更为笼统。

有没有办法在调用导入模块的方法之前自动执行代码?

这将使我更容易编写代码。目前我担心锤击友好的网络服务,所以除非我能找到答案,否则我将不得不实现我自己的控制。


我想通过这样做:

import requests as requests2

...然后在代码中进一步定义一个 requests() 函数,使用特殊参数或一些神奇的未被发现的语法。运行自己的代码后,特殊酱汁会将方法调用转发给别名为 requests2 的真实模块。

这可以做到吗?

最佳答案

你的意思是为另一个模块中的每个函数添加装饰器?你可以用一个类来模拟它:

class RequestsProxy(object):
    def __init__(self):
        self.special_sauce_decorator = special_sauce_indeed()
        self._requests = __import__("requests")

    def __getattr__(self, attrname):
        val = getattr(self._requests, attrname) 
        if callable(val):
            return self.special_sauce_decorator(val)
        return val

示例用法:

>>> def special_sauce_indeed():
        def decorator(f):
                def wrapped(*args, **kwargs):
                        print 'wrapped'
                        return f(*args, **kwargs)
                return wrapped
        return decorator

>>> class OsProxy(object):
        def __init__(self):
            self.special_sauce_decorator = special_sauce_indeed()
            self._requests = __import__("os")

        def __getattr__(self, attrname):
            val = getattr(self._requests, attrname)
            if callable(val):
                return self.special_sauce_decorator(val)
            return val


>>> os = OsProxy()
>>> os.listdir(".")
wrapped
['DLLs', 'Doc', 'faiojerf.py', 'func_counter_test.py', 'include', 'inet_time.py', 'kcol.py', 'Lib', 'libs', 'LICENSE.txt', 'memoize_test.py', 'minpy.py', 'NEWS.txt', 'numpy-wininst.log', 'paren_test.py', 'PIL-wininst.log', 'psycopg2-wininst.log', 'python.exe', 'pythonw.exe', 'pywin32-wininst.log', 'README.txt', 'Removenumpy.exe', 'RemovePIL.exe', 'Removepsycopg2.exe', 'Removepywin32.exe', 'Removescipy.exe', 'Removesetuptools.exe', 'scipy-wininst.log', 'Scripts', 'setuptools-wininst.log', 'slots.py', 'so1.py', 'staticvar.py', 'summing.py', 'taojiwjiot.,py', 'tcl', 'templol.py', 'test.py', 'thunkify_test.py', 'TicketNumberGenerator.py', 'Tools', 'w9xpopen.exe', 'wordcount.py']

关于python - 自动执行模块方法前面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11943307/

相关文章:

python - 在python中排序时列出超出范围的索引

python - Bash 脚本未在 cron-Python 中运行

python - Mask R-CNN Load_weights 函数在 Google Colab 中与tensorflow.compat.v1 不起作用

python - 将 CURL 命令转换为带有表单参数的 POST Python 请求

python-3.x - Python3 - 使用 Socks5 代理的请求

python - 如何用列表中的单词替换重复多次的单个单词?

python - 用于捕获仅有时出现的组的正则表达式

python - Python 网页抓取时的编码问题

Python——Curl 可以工作,而 requests lib 不行

Python:SOAP API 不起作用,我做错了什么?