user1161740
user1161740

Reputation: 81

Load newly installed modules in python script

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

Answers (3)

Crankyadmin
Crankyadmin

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

S.Lott
S.Lott

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.

  1. Use subprocess.Popen to run the sequence of easy_install scripts.

  2. 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

Related Questions