Python中在脚本中引用其他文件函数的实现方法

WBOY
Release: 2016-07-06 13:29:55
Original
1321 people have browsed it

在导入文件的时候,Python只搜索当前脚本所在的目录,加载(entry-point)入口脚本运行目录和sys.path中包含的路径例如包的安装地址。所以如果要在当前脚本引用其他文件,除了将文件放在和脚本同一目录下,还有以下几种方法,

1. 将文件所在位置添加到sys.path中

import sys
sys.path.insert(0, '/path/to/application/app/folder') # or sys.path.append('/path/to/application/app/folder')

import file
Copy after login

2. 在文件目录下新建__init__.py文件然后调用文件

from application.app.folder.file import func_name
Copy after login

init.py文件

a).init.py文件的作用

该文件的主要作用使初始化Python包。如果目录下面包含了该文件,Python解释器就会将该目录当做一个包,下一步就可以使用import语句在别的.py脚本中引用该目录下的文件。一个标准Python模块的结构如下所示:

package/
  __init__.py
  file.py
  file2.py
  subpackage/
    __init__.py
    submodule1.py
    submodule2.py
Copy after login

b). __init__文件可以为空但可以用来建立对包的需求。一般来说会在该文件中写那些类,函数等需要被导入到包水平,从而可以被方便的引用。比如:如果file.py文件中有一个File类,在init.py文件中啥都没写时引用File类需要这样操作:

from package.file import File
Copy after login

如果在__init__.py文件中将file导入包,那就在包水平可以直接引用File类:

# in your __init__.py
from file import File

# in your script
from package import File
Copy after login

此外,还需要注意的一点是__init__.py文件中的all变量。

如果解释器在__init__.py文件中观察到了__all__变量,那么在运行from package import *时就只会引入__all__变量中列出的那些模块。

例如:如果想在上述结构的只引入submodule1模块,那么可以在subpackage/__init__.py文件中定义__all__ = ['submodule1'],当引用subpackage时from subpackage import *就只引入了submodule1模块。

3. 将文件所在目录添加到python的环境变量

export PYTHONPATH=$HOME/pathToYourScripts/:#PYTHONPATH
Copy after login

以上就是小编为大家带来的Python中在脚本中引用其他文件函数的实现方法全部内容了,希望大家多多支持脚本之家~

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!