Home  >  Article  >  Backend Development  >  Detailed explanation of python custom modules

Detailed explanation of python custom modules

高洛峰
高洛峰Original
2017-03-26 18:06:441377browse

Python can add custom modules

Method one:

echo 'export PYTHONPATH='/root/pythondiy/' >> /root/.bashrc # 此目录为你模块的路径
# 然后使用sys模块查看环境变量
import sys
sys.path          # 返回一个列表
['',
 '/usr/local/bin',
 /root/pythondiy',
 '/usr/local/lib/python27.zip',
 '/usr/local/lib/python2.7',
 '/usr/local/lib/python2.7/plat-linux2',
 '/usr/local/lib/python2.7/lib-tk',
 '/usr/local/lib/python2.7/lib-old',
 '/usr/local/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/site-packages/setuptools-28.8.0-py2.7.egg',
 '/usr/local/lib/python2.7/site-packages/pip-9.0.1-py2.7.egg',
 '/usr/local/lib/python2.7/site-packages/IPython/extensions',
 '/root/.ipython']

Method two:

sys.path.append('/root/pythondiy') # This method Temporarily valid

2. Open file difference

open('/etc/passwd').read()                        # 返回全文的是str
open('/etc/passwd').readlines()                   # 返回全文的是一个list
open('/etc/passwd').readline()                    # 每一次读取一行,返回str

3. Custom module call

vim wc.py
#!/usr/bin/python
 
from sys import argv
 
def wc(s):
    chars = len(s)
    words = len(s.split())
    lines = s.count('\n')
    return  lines,words,chars
 
if __name__== '__main__':                      # 只有在执行此脚本时才调用函数。
    with open(argv[1]) as file1:
        print wc(file1.read())
         
vim copy_wc.py
import

4. Execution result

[root@peng pyth]# python wc.py  /etc/passwd    # 返回的是passwd文件统计
(23, 31, 1066)
[root@peng pyth]# python copy_wc.py            # 返回的是hosts文件统计
(2, 10, 158)

5. Import module package

# 需要在包里创建一个__init__.py空文件,也可以是包的描述
touch __init__.py
ipython
from pyth import wc                            # 这样就导入一个模块包

The above is the detailed content of Detailed explanation of python custom modules. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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