Mike
Mike

Reputation: 60771

Python, dynamically invoke script

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

Upvotes: 5

Views: 5161

Answers (2)

rotoglup
rotoglup

Reputation: 5238

While __import__ certainly executes the specified file, it also stores it in the python modules list. If you want to reexecute the same file, you'd have to do a reload.

You can also take a look at the python exec statement that could be more suited to your needs.

From Python documentation :

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

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 993183

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.

Upvotes: 9

Related Questions