How Python references the modules of the parent directory

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.