Omegaspard
Omegaspard

Reputation: 1980

Print a variable from an external lib

I have an external lib. Let's call it ExtarnalLib. This lib contains a method, let's call it method_from_lib. This method take a variable which name is uri. My own code doesn't call the ExternalLib, because it's a code used, from a lib inside a lib and another liber etc....

I would like to print the uri variable.

Would this be possible in python ? If yes how.

I have an intuition it would be possible because with flexmock you can check if a specific function from a specific module is called with some specific args.

Something like :

flexmock(distantLibModuleName.Nameclass).should_receive('methodName').with_args(the_args)

But in my I'm not testing, I'm debugging a code. Normally I would simply follow the stack execution with pdb, but I can't because I only have this problem in prod and I don't have access to a shell.

Upvotes: 4

Views: 214

Answers (2)

gmds
gmds

Reputation: 19885

There is probably a cleaner way to do this, but I have found that inspect.stack should do what you want.

Sample directory structure:

a.py

from b import another_function

def inspect_me(inspect_this):
    another_function()

inspect_me(inspect_this='hello')

b.py

from c import what_was_it

def another_function():
    what_was_it()

c.py

import inspect

result = None

def what_was_it():
    global result
    result = inspect.getouterframes(inspect.currentframe())

From the shell:

import a
import c
import os

[frame_data.code_context for frame_data in c.result if os.path.basename(frame_data.filename) == 'a.py']

Output:

[['    another_function()\n'], 
 ["inspect_me(inspect_this='hello')\n"]]

You can then visually inspect the output.

Upvotes: 1

andreihondrari
andreihondrari

Reputation: 5833

Let's assume you have mod.py where:

def x(uri):
    print("URI", uri)

And then mod2.py which calls the mod.py:x function:

import mod

def y():
    print("Y")
    mod.x(123)

And if we wrap it in our main script:

import mod
import mod2

def wrap(func):
    def wrapper(*args, **kwargs):
        print("PRE", *args, **kwargs)
        func(*args, **kwargs)
        print("POST")

    return wrapper

mod.x = wrap(mod.x)

mod2.y()

Calling the mod2.py:y will yield:

Y
PRE 123
URI 123
POST

Upvotes: 0

Related Questions