python类getargvalues()的实例源码

test_inspect.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)')
test_inspect.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
profile.py 文件源码 项目:data_profiler 作者: numba 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def __init__(self, frame, name=None):

        self.code = c = frame.f_code
        self.filename = c.co_filename
        self.lineno = c.co_firstlineno
        self.name = name or c.co_name
        # builtin methods report as name <method '...' of '...' objects>
        # Extract their real name from that.
        if self.name.startswith('<method '):
            self.name = self.name.split("'", 3)[1]
        arg_info = inspect.getargvalues(frame)
        args=[]
        # There are cases where we can't generate a signature...
        no_signature=False
        if arg_info:
            for a in arg_info.args:
                # FIXME: There are cases where we don't know how to handle arguments.
                #        If 'a' is a list, we bail out...
                if type(a) is list:
                    no_signature=True
                    break
                else:
                    v = arg_info.locals.get(a, None)
                if type(v) == numpy.ndarray:
                    t = 'ndarray(dtype=%s, shape=%s)'%(v.dtype, v.shape)
                # cython-compiled code doesn't report a locals dict, so 'v' may be None
                elif v is None:
                    t = '<unknown>'
                else:
                    t = str(type(v).__name__)
                args.append((a, t))
        self.args = no_signature and None or tuple(args)
proxyplugins.py 文件源码 项目:mitmf 作者: ParrotSec 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def hook(self):
        '''Magic to hook various function calls in sslstrip'''
        #gets the function name and args of our caller
        frame = sys._getframe(1)
        fname = frame.f_code.co_name
        keys,_,_,values = inspect.getargvalues(frame)

        #assumes that no one calls del on an arg :-/
        args = {}
        for key in keys:
            args[key] = values[key]

        #prevent self conflict
        if (fname == "handleResponse") or (fname == "handleHeader") or (fname == "handleEndHeaders"):
            args['request']  = args['self']
            args['response'] = args['self'].client
        else:
            args['request'] = args['self']

        del args['self']

        log.debug("hooking {}()".format(fname))
        #calls any plugin that has this hook
        try:
            for f in self.plugin_mthds[fname]:
                a = f(**args)
                if a != None: args = a
        except Exception as e:
            #This is needed because errors in hooked functions won't raise an Exception + Traceback (which can be infuriating)
            log.error("Exception occurred in hooked function")
            traceback.print_exc()

        #pass our changes to the locals back down
        return args
custom.py 文件源码 项目:azure-cli 作者: Azure 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def update_auth_settings(resource_group_name, name, enabled=None, action=None,  # pylint: disable=unused-argument
                         client_id=None, token_store_enabled=None,  # pylint: disable=unused-argument
                         runtime_version=None, token_refresh_extension_hours=None,  # pylint: disable=unused-argument
                         allowed_external_redirect_urls=None, client_secret=None,  # pylint: disable=unused-argument
                         allowed_audiences=None, issuer=None, facebook_app_id=None,  # pylint: disable=unused-argument
                         facebook_app_secret=None, facebook_oauth_scopes=None,  # pylint: disable=unused-argument
                         twitter_consumer_key=None, twitter_consumer_secret=None,  # pylint: disable=unused-argument
                         google_client_id=None, google_client_secret=None,  # pylint: disable=unused-argument
                         google_oauth_scopes=None, microsoft_account_client_id=None,  # pylint: disable=unused-argument
                         microsoft_account_client_secret=None,  # pylint: disable=unused-argument
                         microsoft_account_oauth_scopes=None, slot=None):  # pylint: disable=unused-argument
    auth_settings = get_auth_settings(resource_group_name, name, slot)

    if action == 'AllowAnonymous':
        auth_settings.unauthenticated_client_action = UnauthenticatedClientAction.allow_anonymous
    elif action:
        auth_settings.unauthenticated_client_action = UnauthenticatedClientAction.redirect_to_login_page
        auth_settings.default_provider = AUTH_TYPES[action]

    import inspect
    frame = inspect.currentframe()
    bool_flags = ['enabled', 'token_store_enabled']
    # note: getargvalues is used already in azure.cli.core.commands.
    # and no simple functional replacement for this deprecating method for 3.5
    args, _, _, values = inspect.getargvalues(frame)  # pylint: disable=deprecated-method

    for arg in args[2:]:
        print(arg, values[arg])
        if values.get(arg, None):
            setattr(auth_settings, arg, values[arg] if arg not in bool_flags else values[arg] == 'true')

    return _generic_site_operation(resource_group_name, name, 'update_auth_settings', slot, auth_settings)
custom.py 文件源码 项目:azure-cli 作者: Azure 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def update_site_configs(resource_group_name, name, slot=None,
                        linux_fx_version=None, php_version=None, python_version=None,  # pylint: disable=unused-argument
                        net_framework_version=None,  # pylint: disable=unused-argument
                        java_version=None, java_container=None, java_container_version=None,  # pylint: disable=unused-argument
                        remote_debugging_enabled=None, web_sockets_enabled=None,  # pylint: disable=unused-argument
                        always_on=None, auto_heal_enabled=None,  # pylint: disable=unused-argument
                        use32_bit_worker_process=None,  # pylint: disable=unused-argument
                        app_command_line=None):  # pylint: disable=unused-argument
    configs = get_site_configs(resource_group_name, name, slot)
    if linux_fx_version:
        if linux_fx_version.strip().lower().startswith('docker|'):
            update_app_settings(resource_group_name, name, ["WEBSITES_ENABLE_APP_SERVICE_STORAGE=false"])
        else:
            delete_app_settings(resource_group_name, name, ["WEBSITES_ENABLE_APP_SERVICE_STORAGE"])

    import inspect
    frame = inspect.currentframe()
    bool_flags = ['remote_debugging_enabled', 'web_sockets_enabled', 'always_on',
                  'auto_heal_enabled', 'use32_bit_worker_process']
    # note: getargvalues is used already in azure.cli.core.commands.
    # and no simple functional replacement for this deprecating method for 3.5
    args, _, _, values = inspect.getargvalues(frame)  # pylint: disable=deprecated-method
    for arg in args[3:]:
        if values.get(arg, None):
            setattr(configs, arg, values[arg] if arg not in bool_flags else values[arg] == 'true')

    return _generic_site_operation(resource_group_name, name, 'update_configuration', slot, configs)
meta_parameter_recorder.py 文件源码 项目:tensorforce 作者: reinforceio 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, current_frame):
        """
        Init the MetaPrameterRecord with "Agent" parameters by passing inspect.currentframe() from Agent Class

        The Init will search back to find the parent class to capture all passed parameters and store
        them in "self.meta_params".

        NOTE: Currently only optimized for TensorBoard output

        TODO: Add JSON Export, TEXT EXPORT

        Args:
            current_frame: frame value from class to obtain metaparameters[= inspect.currentframe()]

        """
        self.ignore_unknown_dtypes = False
        self.meta_params = dict()
        self.method_calling  = inspect.getframeinfo(current_frame)[2]

        _, _, __, self.vals_current = inspect.getargvalues(current_frame)
        # self is the class name of the frame involved
        if 'self' in self.vals_current:  
            self.recorded_class_type = self.vals_current['self']
            # Add explicit AgentName item so class can be deleted
            self.meta_params['AgentName'] = str(self.vals_current['self']) 

        frame_list = inspect.getouterframes(current_frame)

        for frame in frame_list:           
            # Rather than frame.frame (named tuple), use [0] for python2
            args, varargs, keywords, vals =inspect.getargvalues(frame[0])   
            if 'self' in vals:
                if self.recorded_class_type == vals['self']:
                    for i in args:
                        self.meta_params[i] = vals[i]
        # Remove the "CLASS" from the dictionary, has no value "AgentName" contains STR of Class
        del self.meta_params['self']
proxyplugins.py 文件源码 项目:SEF 作者: ahmadnourallah 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def hook(self):
        '''Magic to hook various function calls in sslstrip'''
        #gets the function name and args of our caller
        frame = sys._getframe(1)
        fname = frame.f_code.co_name
        keys,_,_,values = inspect.getargvalues(frame)

        #assumes that no one calls del on an arg :-/
        args = {}
        for key in keys:
            args[key] = values[key]

        #prevent self conflict
        if (fname == "handleResponse") or (fname == "handleHeader") or (fname == "handleEndHeaders"):
            args['request']  = args['self']
            args['response'] = args['self'].client
        else:
            args['request'] = args['self']

        del args['self']

        log.debug("hooking {}()".format(fname))
        #calls any plugin that has this hook
        try:
            if self.plugin_mthds:
                for f in self.plugin_mthds[fname]:
                    a = f(**args)
                    if a != None: args = a
        except Exception as e:
            #This is needed because errors in hooked functions won't raise an Exception + Traceback (which can be infuriating)
            log.error("Exception occurred in hooked function")
            traceback.print_exc()

        #pass our changes to the locals back down
        return args
ProxyPlugins.py 文件源码 项目:SEF 作者: ahmadnourallah 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def hook(self):
        '''Magic to hook various function calls in sslstrip'''
        #gets the function name and args of our caller
        frame = sys._getframe(1)
        fname = frame.f_code.co_name
        keys,_,_,values = inspect.getargvalues(frame)

        #assumes that no one calls del on an arg :-/
        args = {}
        for key in keys:
            args[key] = values[key]

        #prevent self conflict
        args['request'] = args['self']
        del args['self']

        #calls any plugin that has this hook
        try:
            for f in self.pmthds[fname]:
                a = f(**args)
                if a != None: args = a
        except KeyError:
            pass

        #pass our changes to the locals back down
        return args
test_inspect.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)')
test_inspect.py 文件源码 项目:pefile.pypy 作者: cloudtracer 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
cli.py 文件源码 项目:infrasim-compute 作者: InfraSIM 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def node_workspace_exists(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        frame = inspect.currentframe()
        frame_args, _, _, values = inspect.getargvalues(frame)
        node_name = values["args"][1]
        if not Workspace.check_workspace_exists(node_name):
            print "Node {} runtime workspace doesn't exist".format(node_name)
            logger_cmd.warning("cmd res: Node {} runtime workspace doesn't exist".format(node_name))
            return
        return func(*args, **kwargs)
    return wrapper
test_inspect.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)')
test_inspect.py 文件源码 项目:ouroboros 作者: pybee 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
test_inspect.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)')
test_inspect.py 文件源码 项目:ndk-python 作者: gittor 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
utils.py 文件源码 项目:wrfxpy 作者: openwfm 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def traceargs():
    frame = inspect.currentframe()
    args, _, _, values = inspect.getargvalues(frame)
    for i in args:
        print "    %s:\n%s" % (i, pprint.pformat(values[i]))
utils.py 文件源码 项目:schematizer 作者: Yelp 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_current_func_arg_name_values():
    """Return a dict of {parameter name: value} of current function.
    """
    caller_frame = inspect.currentframe().f_back
    arg_info = inspect.getargvalues(caller_frame)

    params = {
        key: arg_info.locals[key] for key in arg_info.args if key != 'self'
    }
    if arg_info.varargs:
        params[arg_info.varargs] = arg_info.locals[arg_info.varargs]
    if arg_info.keywords:
        params.update(arg_info.locals[arg_info.keywords])
    return params
mT2_packages.py 文件源码 项目:LHC_recast 作者: kazuki-sakurai 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def MT2bl_wrapper(lepE, lepPx, lepPy, lepPz, 
                  b1E, b1Px, b1Py, b1Pz, 
                  b2E, b2Px, b2Py, b2Pz,
                  MET_x, MET_y):

    code = """
            double pl[4]  = { lepE, lepPx, lepPy, lepPz};  // El, plx, ply, plz,     (visible lepton)
            double pb1[4] = { b1E, b1Px, b1Py, b1Pz };  // Eb1, pb1x, pb1y, pb1z  (bottom on the same side as the visible lepton)
            double pb2[4] = { b2E, b2Px, b2Py, b2Pz };  // Eb2, pb2x, pb2y, pb2z  (other bottom, paired with the invisible W)
            double pmiss[3] = { 0., MET_x, MET_y };                  // <unused>, pmx, pmy     (missing pT)
            mt2bl_bisect::mt2bl mt2bl;
            mt2bl.set_momenta(pl, pb1, pb2, pmiss);
            return_val = mt2bl.get_mt2bl();
           """

    # Pass all Python arguments to C++
    frame = inspect.currentframe()
    args = inspect.getargvalues(frame)[0]

    lib_MT2bl = inline(code,args,
                    headers=['"MT2bl.h"'],                    
                    include_dirs=["/scratch18/kazuki2/analyses/mT2_packages"],
                    verbose=0                    
                    )

    return lib_MT2bl
mT2_packages.py 文件源码 项目:LHC_recast 作者: kazuki-sakurai 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def MT2_wrapper(m1, p1x, p1y, m2, p2x, p2y, MET_m, MET_x, MET_y):

    code = """
           mt2_bisect::mt2 mt2_event;;           

           double pa[3] = { m1, p1x, p1y };
           double pb[3] = { m2, p2x, p2y };
           double pmiss[3] = { 0, MET_x, MET_y };
           double mn    = MET_m;

           mt2_event.set_momenta(pa,pb,pmiss);
           mt2_event.set_mn(mn);
           //mt2_event.print();

           const double mt2 = mt2_event.get_mt2();
           // std::cout << endl << " mt2 = " << mt2 << std::endl;
           return_val = mt2;
           """

    # Pass all Python arguments to C++
    frame = inspect.currentframe()
    args = inspect.getargvalues(frame)[0]

    # print(args)

    lib_MT2 = inline(code,args,
                    headers=['"mt2_bisect.h"','"mt2_bisect_main.h"'],
                    include_dirs=["/scratch18/kazuki2/analyses/mT2_packages"],
                    verbose=0
                    )

    return lib_MT2


问题


面经


文章

微信
公众号

扫码关注公众号