Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, dynamically invoke script

Tags:

python

command

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
like image 894
Mike Avatar asked Mar 06 '10 02:03

Mike


People also ask

How do you make a Python script dynamic?

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.

How do you call a variable dynamically in Python?

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.

What is dynamic execution in Python?

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.

How do I run a Python script?

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!


1 Answers

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.

like image 176
Greg Hewgill Avatar answered Sep 29 '22 08:09

Greg Hewgill