python
[Python] Using inspect.stack() to get module name, path, function name
import pytest
import logging
import inspect
def test_inspect():
caller = inspect.stack()[1]
logging.info(f"\nThis is caller[3]: {caller[3]}")
def foo():
caller = inspect.stack()[1]
logging.info(f"\nThis is caller[3] inside function: {caller[3]}")
for item in caller:
logging.info(f"\nThis is caller item: {item}")
foo()
Output
-------------------------------- live log call ---------------------------------
08:14:29 INFO
This is caller[3]: pytest_pyfunc_call
08:14:29 INFO
This is caller[3] inside function: test_inspect
08:14:29 INFO
This is caller item: <frame at 0x11138b740, file '/Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py', line 32, code test_inspect>
08:14:29 INFO
This is caller item: /Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py
08:14:29 INFO
This is caller item: 32
08:14:29 INFO
This is caller item: test_inspect
08:14:29 INFO
This is caller item: [' foo()\n']
08:14:29 INFO
This is caller item: 0
08:14:29 INFO
This is caller[3]: pytest_pyfunc_call
08:14:29 INFO
This is caller[3] inside function: test_inspect
08:14:29 INFO
This is caller item: <frame at 0x11138b740, file '/Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py', line 32, code test_inspect>
08:14:29 INFO
This is caller item: /Users/maksim/repos/p4-python-aerofiler/snippets/nodeid.py
08:14:29 INFO
This is caller item: 32
08:14:29 INFO
This is caller item: test_inspect
08:14:29 INFO
This is caller item: [' foo()\n']
08:14:29 INFO
This is caller item: 0
Was this helpful?
Similar Posts
- [Python] Get nodeid, module, function name using Pytest request built-in fixture
- How to get current file path in Python
- How to generate a random number in python using random module
- Python Measure the execution time of small bits of Python code with the timeit module
- [Python] Two ways to import a module
- Column name as alias name SQLAlchemy
- Get a value from DataFrame row using index and column name in pandas