Python可以添加自定义模块
方法一:
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']
方法二:
sys.path.append('/root/pythondiy') # 此方法临时有效
2. open打开文件区别
open('/etc/passwd').read() # 返回全文的是str open('/etc/passwd').readlines() # 返回全文的是一个list open('/etc/passwd').readline() # 每一次读取一行,返回str
3. 自定义模块调用
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. 执行结果
[root@peng pyth]# python wc.py /etc/passwd # 返回的是passwd文件统计 (23, 31, 1066) [root@peng pyth]# python copy_wc.py # 返回的是hosts文件统计 (2, 10, 158)
5. 导入模块包
# 需要在包里创建一个__init__.py空文件,也可以是包的描述 touch __init__.py ipython from pyth import wc # 这样就导入一个模块包
以上是详解python自定义模块的详细内容。更多信息请关注PHP中文网其他相关文章!