5

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

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

1 Comment

Python 3 : exec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.