How to invoke code in another Python file

Source: Internet
Author: User
How to invoke code in another Python file

No matter what language we choose to program, it is impossible to have only one file (except "Hello World"), usually we need to call another file in a file function Yes data and so on, in short, to manipulate the code in other files, in Java, As long as the same file directory, we do not need to import via import, but in Python, we need to import through imports, so that we can apply other files defined in the functions and data and other code. This is what we need to know about our new contact with Python.

The following is an example of two files, for example, we have a.py and b.py two files, when we need to apply the Func () function in the a.py in the b.py file, how to do it, there are two cases, respectively, in the same file directory and not in the same directory under the description.

In the same file directory

A call to the Func () function in the a.py file can be done with the following two statements in the b.py file

Import a #引用模块
A.func ()

or a

Import a# Application Module
From a import func #引用模块中的函数
Func () #这里调用函数就不需要加上模块名的前缀了

Under Different file directories

If you are not in the same directory, Python cannot find it, you must set up a lookup path, add the folder that contains the module to the system lookup path

Import Sys
Sys.path.append (' path where ' a.py is located ')
Import a
A.func ()

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to invoke code in another Python file

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.