Home > Net >  Identifying the calling python script in the called python script and print
Identifying the calling python script in the called python script and print

Time:01-21

How can I print the name of the script that called the current script in python? Are there any built-in functions to identify the source script?

Example: if x.py calls y.py and y.py calls z.py, I want to print x.py in z.py as x.py initiated the function.

CodePudding user response:

Yes, you can use the __file__ attribute to access the name of the current python script from within the script. The __file__ attribute is a built-in attribute in python which gives the path of the current running script. You can simply use it to print the name of the calling python script like in script z.py, you can use the following line of code to print the name of the calling script (in this case, x.py)

print(__file__)

Also, if you want to print the name of the script without the file extension, you can use the following code snippet:

import os
print(os.path.basename(__file__).split(".")[0])

And if you want to know the name of the script that initiated the function you can use traceback library.

import traceback

def print_caller_name():
    tb = traceback.extract_stack()
    print(tb[-2][2])

So, when you call the print_caller_name() function, it will print the name of the script that called the function.

Note; if you call z.py from y.py and y.py is called by x.py then print_caller_name() will print x.py as output.

CodePudding user response:

Yes, you can use an inbuilt function in Python that can be used to identify the name of the calling Python script. You can use the inspect module to capture the filename of the calling script. Specifically, you can use the inspect.stack() function to get a list of the call stack, and then use the inspect.stack()[1][1] to get the filename of the calling script.

Below is an example:

import inspect

def print_calling_script_name():
    print(inspect.stack()[1][1])

print_calling_script_name()

The above will give the name of the script that called the print_calling_script_name() function. Note that the value 1 in inspect.stack()[1] is the index of the calling script in the call stack.

If you want the name of the script that called the script that called the function, you can use inspect.stack()[2][1].

  • Related