tags:

views:

68

answers:

2

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
+6  A: 

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.

Greg Hewgill
thanks greg. bonus points if you can show how to do this if the python file lies in another directory than the script
Mike
@Mike: sure, modify `sys.path`, perhaps like this: `sys.path.append("/your/module/directory")`
Greg Hewgill
A: 

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.

rotoglup