简体   繁体   中英

Import python package after installing it with setup.py, without restarting?

I have a package that I would like to automatically install and use from within my own Python script.

Right now I have this:

>>> # ... code for downloading and un-targzing

>>> from subprocess import call
>>> call(['python', 'setup.py', 'install'])
>>> from <package> import <name>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named <package>

Then I can continue like this:

>>> exit()
$ python
>>> from <package> import <name>

And it works just fine. For some reason, Python is able to pick up the package just fine if I restart after running the setup.py file, but not if I don't. How can I make it work without having the restart step in the middle?

(Also, is there a superior alternative to using subprocess.call() to run setup.py within a python script? Seems silly to spawn a whole new Python interpreter from within one, but I don't know how else to pass that install argument.)

Depending on your Python version, you want to look into imp or importlib .

eg for Python 3, you can do:

from importlib.machinery import SourceFileLoader
directory_name = # os.path to module
# where __init__.py is the module entry point
s = SourceFileloader(directory_name, __init__.py).load_module() 

or, if you're feeling brave that your Python path knows about the directory:

map(__import__, 'new_package_name')

Hope this helps,

I downloaded from seaborn from GitHub.

Through command prompt, cd to downloads\\seaborn folder

python install setup.py

Then using spyder from anaconda, checked if it was installed by running the following in a console

import pip
sorted(["%s==%s" % (i.key, i.version)
     for i in pip.get_installed_distributions()])

Seeing that it was not there, go to tools and select "Update module names list"

Again trying the previous code in a python console, the lib was still not showing.

Restarting Spyder and trying import seaborn worked.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM