Python dynamically call script

I want to run a python script from another. Internally, I mean that any state change from a child script affects the parent state. Therefore, if a variable is set in a child, it changes in the parent.

You can usually do something like

import module 

But the problem is that the executed child script is an argument of the parent script, I donโ€™t think you can use import with a variable

Something like that

 $python run.py child.py 

That would be what I would expect

 #run.py #insert magic to run argv[1] print a #child.py a = 1 $python run.py child.py 1 
+4
source share
2 answers

You can use the __import__ function, which allows you to dynamically import a module:

 module = __import__(sys.argv[1]) 

(You may need to remove the trailing .py or not specify it on the command line.)

From the Python documentation:

Direct use of __import__() is rare, unless you want to import a module whose name is known only at run time.

+8
source

Although __import__ certainly executes the specified file, it also saves it in the python module list. If you want to re-execute the same file, you will need to reload.

You can also take a look at the python exec statement, which may be more suitable for your needs.

From the Python documentation:

This statement supports the dynamic execution of Python code. The first expression must evaluate either a string, or an open object, or a code object.

+1
source

Source: https://habr.com/ru/post/1303308/


All Articles