简体   繁体   English

使用setup.py安装后导入python程序包,而无需重新启动吗?

[英]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. 我有一个要在自己的Python脚本中自动安装和使用的软件包。

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. 由于某种原因,如果我在运行setup.py文件后重新启动,Python可以很好地拾取该软件包,但如果不这样做,则可以。 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.) (此外,有没有比使用subprocess.call()在python脚本中运行setup.py更好的选择了?似乎很愚蠢地从一个内部生成一个全新的Python解释器,但是我不知道该如何传递该安装参数)。

Depending on your Python version, you want to look into imp or importlib . 根据您的Python版本,您需要查看impimportlib

eg for Python 3, you can do: 例如,对于Python 3,您可以执行以下操作:

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: 或者,如果您对自己的Python路径知道该目录感到很勇敢:

map(__import__, 'new_package_name')

Hope this helps, 希望这可以帮助,

I downloaded from seaborn from GitHub. 我是从GitHub的seaborn下载的。

Through command prompt, cd to downloads\\seaborn folder 通过命令提示符,cd到downloads \\ seaborn文件夹

python install setup.py

Then using spyder from anaconda, checked if it was installed by running the following in a console 然后使用anaconda的spyder,通过在控制台中运行以下命令来检查是否已安装

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. 再次在python控制台中尝试前面的代码,库仍然没有显示。

Restarting Spyder and trying import seaborn worked. 重新启动Spyder并尝试import seaborn

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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