Reputation: 81
I am writing a python script which automatically sets up a django web server environment.
In the script, I am installing a new modules using
for package in packages:
os.system("%s %s" % ('easy_install', package))
This works fine. My only issue is that I want to use these newly installed packages in the same script using
package = __import__(package)
This does not work though, and I receive an ImportError: No module named reportlab (for example)
If I run the script again, the script works as I assume all of the newly installed packages are on the system path. I was hoping there is a way that I can import the new modules without restarting the script though.
I tried reload(sys) but it didn't help me. I can hack it by manually appending to sys.path or by starting a new python script using os.system(), but I would prefer a cleaner solution.
Upvotes: 2
Views: 270
Reputation: 341
You need to reload site
module, not sys
:
"Importing this module will append site-specific paths to the module search path and add a few builtins."
Also, consider using of importlib.import_module
instead of __import__
:
This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().
Upvotes: 0
Reputation: 155
Have a look at Fabric, by the looks of things it'll make your life a lot easier. Django integration here.
Upvotes: 0
Reputation: 391952
There cannot be a cleaner solution. You're installing a package, which leads to an update to the system path. You must either tinker with the path or start a sub-script that works in a new environment.
Also. Don't use os.system
. Please use subprocess
.
The least risky way to do this is to have a "master" script which only does two kinds of things.
Use subprocess.Popen
to run the sequence of easy_install scripts.
Use subprocess.Popen
to do the rest of the work after all the easy_install scripts. Since this is a separate process, it can build a separate Python PATH with all of the new packages in it.
Upvotes: 3