1, to the home directory for the subject, to jump
Sys.path.append (Os.path.dirname (__file__) + Os.sep + ' ... /') from config import swordfishconffrom utils import logfrom utils.mysql_base import mysqlbase
Add the program's home directory to Sys.path, then use this as a jump.
In the example, for the encapsulated Mysqlbase class access, the Utils package is accessed first, and then the Mysqlbase class is found from the mysql_base.py
Cons: When looking at the code, the current script and package relationship is not very clear, need to be transferred to home, and then from home to find one by one
Question: How to directly see the relationship between the current script and the package, rather than passing through the home
2. Using Absolute_path
Configuration Pythonpath:
Export Pythonpath=/data1/guosong/opdir/20141017/test: $PYTHONPATH
code example:
.| --__init__.py|--lib| | --__init__.py| | --pack1| | | --__init__.py| | | --a.py| | '--aa.py| '--pack2| | --__init__.py| | --b.py|--test.py
The code for test.py is as follows:
[Email protected] ice_test_m test]# more test.py#!/usr/bin/env python2.7#-*-coding:utf8-*-from __future__ Import Absol Ute_importfrom lib.pack1.a Import aobjectif __name__ = = ' __main__ ': Aobject.printword ()
Referencing a class aobject from lib.pack1.a, calling its static method
a.py content:
[Email protected] ice_test_m pack1]# more a.py#!/usr/bin/env python2.7#-* coding:utf8-*-from __future__ Import Absolute _import#from. A import bobjectfrom. pack2.b Import Bobjectclass Aobject (object): @classmethod def printword (self): B = bobject (' A call B Class ')
A.py is called in the previous directory pack2.b Bobject
b.py content is:
[Email protected] ice_test_m pack2]# more b.py#!/usr/bin/env python2.7#-* coding:utf8-*-#from __future__ Import Absolut E_importclass Bobject (object): def __init__ (self,bstr): print "b:%s"% BSTR
Benefits: Skip home and jump directly to relative path
3, Absolute_path Introduction
4. Problems encountered using Absolute_path 4.1, valueerror:attempted relative import in Non-package
4.2. valueerror:attempted relative import beyond TopLevel package
Resources
1, http://blog.csdn.net/chinaren0001/article/details/7338041
Path reference for Python