Importing user defined modules in python from a directory

人走茶凉 提交于 2019-11-27 06:15:46

问题


I'm trying to import a module I wrote in python that just prints out a list containing numbers. The issue I'm having is that I want to be able to import it from a separate directory but the answers I have read so far don't seem to be working for my situation.

For example, given I want to import printnumbers.py from a directory in my documents folder I am supposed to implement the following:

    import sys
    sys.path.append('/home/jake/Documents')
    import printnumbers.py

This snipit of code results in a "Import error" telling me that the specified module does not exist. I'm not exactly sure where to proceed from here, I have checked multiple times to make sure it's the right spelling for the path as well as for the module name. I'm still trying to understand exactly what appending to the "sys.path" does. From what I understand it's telling the program to search for modules in that directory?

Thanks for anyone who answers my rather novice question. I'm just looking for a better understanding of it that the python documentation isn't providing for my frame of mind.


回答1:


When the file is printnumbers.py, the module is called printnumbers (without the .py). Therefore use

import printnumbers

import sys
sys.path.append('/home/jake/Documents')

appends '/home/jake/Documents' to the end of sys.path. The directories listed in sys.path are searched (in the order listed) whenever an import statement causes Python to search for a module. (Already imported modules are cached in sys.modules, so Python does not always need to search sys.path directories to import a module...)

So if you have a file /home/jake/Documents/printnumbers.py, then import printnumbers will cause Python to import it provided there is no other file named printnumbers.py in a directory listed in sys.path ahead of /home/jake/Documents/.

Note that injecting directories into sys.path is not the usual way to set up Python to search for modules. Usually it is preferable to add /home/jake/Documents to your PYTHONPATH environment variable. sys.path will automatically include the directories listed in the PYTHONPATH environment variable.




回答2:


and one more thing, use an empty __ init __.py file in you directory to make it as a python package (only then Python will know that this directory is a Python package directory other than an ordinary directory). Thus you can import modules from that package from different directory.



来源:https://stackoverflow.com/questions/37516579/importing-user-defined-modules-in-python-from-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!