Today, do a test that would like to refer to the upper directory in the current Python module; Uh, a search.
Let's look at the directory situation:
[Email protected] test]# tree.├──t1.py├──t2│└──t2.py└──xxu└──test.py2 directories, 3 files
In fact, the first thing you want to do is to call the t1.py function in test.py:
Direct use of the effect:
[email protected] xxu]# cat test.py #/usr/bin/env python#coding:utf-8import t1print t1.t1 () [[email protected] xxu]# Pyth On test.py Traceback (most recent call last): File "test.py", line 4, in <module> import t1importerror:no modul E named T1
After a search, the discovery principle is that by os.path.append ("path") way, the Python environment variable is switched to the previous level, you can directly refer to the T1 module
[[email protected] xxu]# cat test.py #/usr/bin/env python#coding:utf-8import syssys.path.append ("/test/test") Import T1print t1.t1 () [[email protected] xxu]# python test.py t1 test
Absolute path must be used
The second type of extension:
is to call the function in t2.py through test.py.
The principle is to create an empty file in the T2 directory __init__.py, so Python recognizes T2 this directory is a package, or just for the directory
[Email protected] test]# tree.├──t1.py├──t1.pyc├──t2│├──__init__.py│└──t2.py└──xxu└──test.py2 Directorie S, 5 files
[email protected] xxu]# cat. /t2/t2.py #/usr/bin/env python#coding:utf-8def T2 (): print "t2 test!!!" [Email protected] xxu]# vim test.py [[email protected] xxu]# python test.py t1 TESTT2 Test!!! None
This article from "next door Lao Zhang" blog, reprint please contact the author!
How Python references the modules of the parent directory