A few questions regarding Pythons 'import' feature
I just downloaded Beautiful Soup and I've decided I'll make a small library (is that what they call them in Python?) that will return results of a movie given and IMDB movie search.
My question is, how exactly does this import thing work?
For example, I downloaded BeautifulSoup and all it is, is a .py file. Does that file have to be in the same folder as the my python application开发者_如何学JAVA (my project that will use the library)?
BeautifulSoup.py will need to be placed somewhere on the Python search path, which is available to you in the sys.path
array. Note that the current directory is always included in this array (as the empty string).
>>> import sys
>>> sys.path
['', 'C:\\Windows\\system32\\python26.zip', 'c:\\python26\\DLLs', 'c:\\python26\\lib', 'c:\\python26\\lib\\plat-win', 'c
:\\python26\\lib\\lib-tk', 'c:\\python26', 'c:\\python26\\lib\\site-packages', 'c:\\python26\\lib\\site-packages\\win32'
, 'c:\\python26\\lib\\site-packages\\win32\\lib', 'c:\\python26\\lib\\site-packages\\Pythonwin']
For Ubuntu, you can search for packages with the command
apt-cache search beautifulsoup
This should yield
python-beautifulsoup - error-tolerant HTML parser for Python
So the easiest way to install BeautifulSoup for ubuntu would be to run
sudo apt-get install python-beautifulsoup
Once you do this, you can put
import BeautifulSoup
in any of your scripts and your python installation will find the module.
See the module search path. For your case, placing the .py file in the same folder will work.
Python modules are top level entities in python programs that can be imported (analogous to C files). There is a load path which contains a list of directories to search for modules when you're importing them. I'd recommend that you go through the modules section of the official tutorial for details (and through the whole tutorial as well).
Have a look at the documentation on packages. When you import a package, python searches within sys.path
, so you must place Beautiful Soup within the path, or append a new directory to the path.
Example:
import sys
print "Before:\n", sys.path
sys.path.append('/some/directory')
print "After:\n", sys.path
Might not be relevant, but have you considered using imdbpy? Last time I used it it worked pretty well...
精彩评论