[英]How to import libraries from source code in python?
I am trying to write a python script that I could easily export to friends without dependency problems, but am not sure how to do so. 我正在尝试编写一个python脚本,可以轻松地将其导出给朋友而没有依赖关系问题,但是不确定如何做到这一点。 Specifically, my script relies on code from BeautifulSoup, but rather than forcing friends to have to install BeautifulSoup, I would rather just package the src for BeautifulSoup into a Libraries/ folder in my project files and call to functions from there.
具体来说,我的脚本依靠的是BeautifulSoup的代码,而不是强迫朋友必须安装BeautifulSoup,我宁愿只是将BeautifulSoup的src打包到我的项目文件中的Libraries /文件夹中,然后从那里调用函数。 However, I can no longer simply "import bs4."
但是,我不能再简单地“导入bs4”了。 What is the correct way of going about this?
正确的解决方法是什么?
Thanks! 谢谢!
A common approach is ship a requirements file with a project, specifying which version of which library is required. 一种常见的方法是将需求文件与项目一起提供,指定需要哪个库的版本。 This file is (by convention) often named
requirements.txt
and looks something like this: 该文件(按照惯例)通常命名为
requirements.txt
,看起来像这样:
MyApp
BeautifulSoup==3.2.1
SomeOtherLib==0.9.4
YetAnother>=0.2
(The fictional file above says: I need exactly BeautifulSoup 3.2.1, SomeOtherLib 0.9.4 and any version of YetAnother greater or equal to 0.2). (上面的虚构文件说:我完全需要BeautifulSoup 3.2.1,SomeOtherLib 0.9.4以及任何更大或等于0.2的YetAnother版本)。
Then the user of this project can simply take you library, (create a virtualenv ) and run 然后,该项目的用户可以简单地获取您的库(创建virtualenv )并运行
$ pip install -r requirements.txt
which then will fetch all libraries and makes them available either system-wide of project-wide (if virtualenv is used). 然后它将获取所有库,并使它们在系统范围或项目范围内可用(如果使用virtualenv)。 Here's a random python project off github, having a requirements file:
这是github上的一个随机python项目,有一个需求文件:
The nice thing about this approach is that you'll get your transitive dependencies resolved automatically. 这种方法的好处是,您可以自动解决传递依赖。 Also, if you use virtualenv, you'll get a clean separation of your projects and avoid library version collisions.
此外,如果您使用virtualenv,则可以将项目完全分开,并避免库版本冲突。
您必须先将Libraries/
(首先转换为绝对路径)添加到sys.path
然后再尝试导入其下的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.