I want to run a python script from within another. By within I mean any state changes from the child script effect the parent's state. So if a variable is set in the child, it gets changed in the parent.
Normally you could do something like
import module
But the issue is here the child script being run is an argument to the parent script, I don't think you can use import with a variable
Something like this
$python run.py child.py
This would be what I would expect to happen
#run.py
#insert magic to run argv[1]
print a
#child.py
a = 1
$python run.py child.py
1
Method 1: exec() The exec() function can take any source code as a string and run it within your script. It's the perfect way to dynamically create a function in Python! ? Python's built-in exec() executes the Python code you pass as a string or executable object argument.
Using exec() method to create dynamically named variables Here we are using the exec() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
You can use the __import__
function which allows you to import a module dynamically:
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, except in cases where you want to import a module whose name is only known at runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With