Reference custom modules in Python

Source: Internet
Author: User

Reference custom modules in Python

After learning Python for a short period of time, it has never been stuck in simple syntax and cannot really understand the power of Python. I learned how to reference a custom module today. When a module is referenced, the compiler will first find the referenced module in the current directory, and then go to the sys. path and Python installation directories. If not, an error will be reported.

In the first case, your module is in the same directory as the module you want to use. Hello. py is a module with the Hello, World printing method Hello (). Test. py is a test program that references the Hello () method in hello. py. It can be referenced directly because it is in the same directory as the module.

Hello. py

Def hello (): print "Hello World"
Test. py
Import HelloHello. hello ()

In the second case, the module is somewhere else. Method 1: first reference sys to modify sys. path. In fact, the module path is added to sys. path.

Test. py

Import syssys. path. append ('e:/workspace/Modules ') import HelloHello. hello ()

Method 2: add the path to the environment variable. This is permanent. You can create a folder for storing modules and add the path of this folder to the environment variable, it can work at a time, never causing trouble, and also facilitates management.

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.