Python calling script name

Get name of current script in Python

You can use __file__ to get the name of the current file. When used in the main module, this is the name of the script that was originally invoked.

If you want to omit the directory part (which might be present), you can use os.path.basename(__file__) .

For completeness’ sake, I thought it would be worthwhile summarizing the various possible outcomes and supplying references for the exact behaviour of each.

The answer is composed of four sections:

  1. A list of different approaches that return the full path to the currently executing script.
  2. A caveat regarding handling of relative paths.
  3. A recommendation regarding handling of symbolic links.
  4. An account of a few methods that could be used to extract the actual file name, with or without its suffix, from the full file path.

Extracting the full file path

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute may be missing for certain types of modules, such as C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’ . If no script name was passed to the Python interpreter, argv[0] is the empty string.

import inspect source_file_path = inspect.getfile(inspect.currentframe()) 
import lib_programname # this returns the fully resolved path to the launched python program path_to_program = lib_programname.get_path_executed_script() # type: pathlib.Path 

Handling relative paths

When dealing with an approach that happens to return a relative path, it might be tempting to invoke various path manipulation functions, such as os.path.abspath(. ) or os.path.realpath(. ) in order to extract the full or real path.

Читайте также:  Html input type radio get value

However, these methods rely on the current path in order to derive the full path. Thus, if a program first changes the current working directory, for example via os.chdir(. ) , and only then invokes these methods, they would return an incorrect path.

If the current script is a symbolic link, then all of the above would return the path of the symbolic link rather than the path of the real file and os.path.realpath(. ) should be invoked in order to extract the latter.

Further manipulations that extract the actual file name

os.path.basename(. ) may be invoked on any of the above in order to extract the actual file name and os.path.splitext(. ) may be invoked on the actual file name in order to truncate its suffix, as in os.path.splitext(os.path.basename(. )) .

From Python 3.4 onwards, per PEP 428, the PurePath class of the pathlib module may be used as well on any of the above. Specifically, pathlib.PurePath(. ).name extracts the actual file name and pathlib.PurePath(. ).stem extracts the actual file name without its suffix.

This will print foo.py for python foo.py , dir/foo.py for python dir/foo.py , etc. It’s the first argument to python . (Note that after py2exe it would be foo.exe .)

Источник

Python calling script name

Last updated: Feb 22, 2023
Reading time · 6 min

banner

# Table of Contents

# Call a function by a String name in Python

To call a function by a string name:

  1. Import the module the function is defined in.
  2. Use the getattr() function to get the function.
  3. Call the function.

If you need to call a function given a string name and the function is defined in a different module, you first have to import the module.

Copied!
import example_module func = getattr(example_module, 'example_function') print(func('ab', 'cd')) # 👉️ 'abcd'

The code sample assumes that there is a module named example_module located in the same directory.

Copied!
def example_function(a, b): return a + b

call function by string name

Once we have the module that defines the function imported, we can use the getattr() function to get the function by a string name.

The getattr function returns the value of the provided attribute of the object.

The function takes the following parameters:

Name Description
object the object whose attribute should be retrieved
name the name of the attribute
default a default value for when the attribute doesn’t exist on the object

The getattr() function will return the function, so the last step is to invoke it and provide all the required arguments.

Copied!
import example_module func = getattr(example_module, 'example_function') print(func('ab', 'cd')) # 👉️ 'abcd'

If the function is defined in the same module, use the globals() function.

# Call a function by a String name using globals()

This is a three-step process:

  1. Use the globals() function to get a dictionary containing the current scope’s global variables.
  2. Use the string as a dictionary key to get the function.
  3. Call the function.
Copied!
def do_math(a, b): return a + b func = globals()['do_math'] print(func(10, 5)) # 👉️ 15

call function by string name using globals

The globals function returns a dictionary that implements the current module namespace.

Copied!
def do_math(a, b): return a + b # , '__spec__': None, '__annotations__': <>, '__builtins__': , '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, 'do_math': > print(globals())

You can use the string to access the specific key in the dictionary.

There is a key with the function’s name that points to the actual function.

If a function with the given name doesn’t exist in the module, you’d get a KeyError exception.

The last step is to use parentheses to call the function providing it any arguments it requires.

# Call a function by a String name using a dictionary

Alternatively, you could define a dictionary that maps function names to the actual functions.

Copied!
def do_math(a, b): return a + b functions_dict = 'do_math': do_math, > function_name = 'do_math' if function_name in functions_dict: # 👇️ 15 print(functions_dict[function_name](10, 5))

call function by string name using dictionary

The functions_dict dictionary has function names as keys and the actual functions as values.

If if statement checks if the specified string is present in the dictionary before calling the function.

You can use the getattr() function if you need to call a class method by a string name.

# Call a class method by a String name in Python

To call a class method by a string name:

  1. Instantiate the class to get an object.
  2. Use the getattr() function to get access to the method.
  3. Call the method.
Copied!
class Employee(): def __init__(self, first, last): self.first = first self.last = last def get_name(self): return self.first + ' ' + self.last cls = globals()['Employee'] emp1 = cls('bobby', 'hadz') func = getattr(emp1, 'get_name') print(func()) # 👉️ bobby hadz

call class method by string name

If you have to call a method by a string name from within another class method, you would pass self as the first argument to the getattr() function.

If the class is defined in a different module, you would have to import it.

You can either import the class directly or use the importlib.import_module() method.

# Importing a class and calling a method by string name

Here is an example that imports the class directly and calls a method by a string name.

Copied!
import example_module cls = getattr(example_module, 'Employee') emp1 = cls('bobby', 'hadz') func = getattr(emp1, 'get_name') print(func()) # 👉️ bobby hadz

The code sample assumes that there is a module named example_module located in the same directory.

Copied!
class Employee(): def __init__(self, first, last): self.first = first self.last = last def get_name(self): return self.first + ' ' + self.last

We used the getattr() function to get the class and then used the function to get the method.

The last step is to invoke the method.

# Using importlib to import the module before calling the method by string name

Here is an example that uses the importlib.import_module() method to import the module before calling a specific method given a string name.

Copied!
import importlib module = importlib.import_module('example_module') cls = getattr(module, 'Employee') emp1 = cls('bobby', 'hadz') func = getattr(emp1, 'get_name') print(func()) # 👉️ bobby hadz

The code sample assumes that there is a module named example_module in the same directory and the module defines an Employee class.

The importlib.import_module method takes the name of a module and imports it.

The name argument can be absolute or relative, e.g. pkg.module or ..module .

If you use a relative package name, e.g. ..module , you have to pass a second argument to the import_module() method, e.g. import_module(‘..module’, pkg.subpkg’) imports pkg.module .

# Call a function by a String name using locals()

If the function you need to call is located in the same module, you can also use the locals() dictionary.

Copied!
def example_function(a, b): return a + b # 👇️ 105 print( locals()['example_function'](50, 55) )

This approach is similar to using the globals() dictionary, however, the locals() function returns a dictionary that contains the current scope’s local variables, whereas the globals dictionary contains the current module’s namespace.

# Using globals() vs locals() to call a function by string name

Here is an example that demonstrates the difference between the globals() and the locals() dictionaries.

Copied!
def example_function(): return 'GLOBAL example function' def call_function_by_string_name(): def example_function(): return 'LOCAL example function' # 👇️ GLOBAL example function print(globals()['example_function']()) print('-' * 30) # 👇️ LOCAL example function print(locals()['example_function']()) call_function_by_string_name()

The function with the name example_function is defined in the global and local scopes.

When we used the globals() dictionary, we called the global function (the one from the outer scope).

When we used the locals() dictionary, we called the local function (the one that is defined inside the function).

# Call a function by a String name using eval()

You can also use the eval() function to call a function by string name.

Copied!
def greet(name): return f'hello name>' function_name = 'greet' func = eval(function_name) print(func) # 👉️ print(func('Bobby Hadz')) # 👉️ hello Bobby Hadz

The eval function takes an expression, parses it and evaluates it as a Python expression using the globals and locals dictionaries as the global and local namespace.

The eval() function should only be used with trusted code. Don’t use eval() with user-generated data.

The eval() function basically tries to run the given expression, so it should never be used with untrusted code.

# Call a function by a String name using exec()

You can also use the exec() function to call a function by string name.

Copied!
def greet(name): return f'hello name>' function_name = 'greet' exec(f'my_func=function_name>') print(my_func) # 👉️ print(my_func('Bobby Hadz')) # 👉️ hello Bobby Hadz

Make sure to only use this approach if you can trust the data stored in the dictionary. Never use the exec() function with untrusted user input.

The exec function supports dynamic execution of Python code.

The function takes a string, parses it as a suite of Python statements and runs the code.

We assigned the result of evaluating the string name to the my_func variable.

You can then use the my_func variable to invoke the function as shown in the code sample.

When using this approach, you are likely to get linting warnings because the variable is declared implicitly using exec() .

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью