Noob Question: How to import some imodule in Python?
I am using Python 2.5 on CentOS 5.5
I have got开发者_运维技巧 a file called MultipartPostHandler.py
, I am supposed to use it like this:
import MultipartPostHandler
But I dont know where should I put the file MultipartPostHandler.py
so I can use it. Thanks a lot!
http://docs.python.org/tutorial/modules.html#the-module-search-path
When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python.
Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default. This allows Python programs that know what they’re doing to modify or replace the module search path.
So, you have to put it into the current directory or use sys.path to show your program where the searched module is.
The easiest is to put it in the same folder as the code you're writing.
If you got it from somebody who provides an installer, then to be safe, just run the installer.
If it's just something you grabbed specifically for this project, put it in the same folder as the .py
files that you're writing.
Otherwise (if you're planning to use it for a few projects and don't want to copy/paste the file), the safest place to put it is probably in the /lib/site-packages
sub-directory of the directory where Python is installed.
The easiest - yes, is to put it in the same directory where you have the importer python code. Also, you can export PYTHONPATH
environment variable which points to the directory (or directories separated by :
) where you have MultipartPostHandler.py
. Another option: make it distributable. This will be useful if you are going to publish your code.
精彩评论