第二模块:函数编程 常用模块

  • 01-常用模块学习-小鸡汤
  • 02-常用模块学习-模块种类和导入方法
  • 03-常用模块学习-模块的导入路径
  • 04-常用模块学习-开源模块学习的安装方式
  • 05-常用模块学习-使用国内源下载模块
  • 06-常用模块学习-包及跨模块导入
  • 07-常用模块学习-跨模块导入2
  • 08-常用模块学习-相对导入
  • 09-常用模块学习-time模块详解
  • 10-常用模块学习-datetime模块详解
  • 11-常用模块学习-random模块详解
  • 12-常用模块学习-os模块详解
  • 13-常用模块学习-sys模块详解
  • 14-常用模块学习-shutil模块详解
  • 15-常用模块学习-序列化模块详解
  • 16-常用模块学习-序列化json模块详解
  • 17-常用模块学习-序列化pickle模块详解
  • 18-常用模块学习-序列化shelve模块详解
  • 19-常用模块学习-xml处理模块详解
  • 20-常用模块学习-自动创建xml文档
  • 21-常用模块学习-configparser模块详解_batch
  • 22-常用模块学习-hashlib加密模块详解
  • 23-常用模块学习-subprocess模块详解
  • 24-常用模块学习-subprocess模块详解2
  • 25-常用模块学习-logging模块基础
  • 26-常用模块学习-logging模块进阶
  • 27-常用模块学习-logging日志过滤和日志文件自动截取
  • 28-常用模块学习-re正则表达式讲解
  • 29-常用模块学习-re匹配语法
  • 30-常用模块学习-re正则表达式公式讲解1
  • 31-常用模块学习-re正则表达式公式讲解2
  • 32-常用模块学习-re正则表达式公式讲解3
  • 33-常用模块学习-re正则表达式公式讲解4
  • 34-常用模块学习-re正则表达式公式讲解5
  • 35-常用模块学习-re正则表达式公式讲解6
  • 36-常用模块学习-re正则表达式公式讲解7
  • 37-常用模块学习-软件开发目录规范
  • 39-常用模块学习-作业需求

01-常用模块学习-小鸡汤

1、模块概念的引入——工具箱;

2、节目推荐-晓说;

  • 《晓说》是2012年3月高晓松开始主持的网络脱口秀节目。
  • 在每周30-40分钟一集的节目中,《晓说》每期由主持人高晓松谈论一个热门话题,打造视频化的“高晓松专栏文章”。
  • 2017年4月7日,停播了将近3年的《晓说》已在优酷重新开播。

02-常用模块学习-模块种类和导入方法

1、什么是模块?!

C:\Users\Administrator\PycharmProjects\LFXC2018\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.3\helpers\pydev\pydevconsole.py" 58035 58036
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['C:\\Users\\Administrator\\PycharmProjects\\LFXC2018', 'C:/Users/Administrator/PycharmProjects/LFXC2018'])
PyDev console: starting.
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
help('modules')
Please wait a moment while I gather a list of all available modules...
__future__          _winapi             imp                 selectors
_ast                abc                 importlib           setup
_asyncio            aifc                inspect             setup_cython
_bisect             antigravity         interpreterInfo     setuptools
_blake2             argparse            io                  shelve
_bootlocale         array               ipaddress           shlex
_bz2                ast                 itertools           shutil
_codecs             asynchat            json                signal
_codecs_cn          asyncio             keyword             site
_codecs_hk          asyncore            lib2to3             sitecustomize
_codecs_iso2022     atexit              linecache           smtpd
_codecs_jp          audioop             locale              smtplib
_codecs_kr          backend_interagg    logging             sndhdr
_codecs_tw          base64              lzma                socket
_collections        bdb                 macpath             socketserver
_collections_abc    binascii            macurl2path         sqlite3
_compat_pickle      binhex              mailbox             sre_compile
_compression        bisect              mailcap             sre_constants
_csv                builtins            marshal             sre_parse
_ctypes             bz2                 math                ssl
_ctypes_test        cProfile            mimetypes           stat
_datetime           calendar            mmap                statistics
_decimal            cgi                 modulefinder        string
_distutils_findvs   cgitb               msilib              stringprep
_dummy_thread       chardet             msvcrt              struct
_elementtree        chunk               multiprocessing     subprocess
_functools          cmath               netrc               sunau
_hashlib            cmd                 nntplib             symbol
_heapq              code                nt                  symtable
_imp                codecs              ntpath              sys
_io                 codeop              nturl2path          sysconfig
_json               collections         numbers             tabnanny
_locale             colorsys            opcode              tarfile
_lsprof             compileall          operator            telnetlib
_lzma               concurrent          optparse            tempfile
_markupbase         configparser        os                  test
_md5                contextlib          parser              test_pydevd_reload
_msi                copy                pathlib             tests_pydevd
_multibytecodec     copyreg             pdb                 tests_pydevd_mainloop
_multiprocessing    crypt               pickle              tests_pydevd_python
_opcode             csv                 pickletools         textwrap
_operator           ctypes              pip                 this
_osx_support        curses              pipes               threading
_overlapped         datetime            pkg_resources       time
_pickle             dbm                 pkgutil             timeit
_pydecimal          decimal             platform            tkinter
_pydev_bundle       difflib             plistlib            token
_pydev_imps         dis                 poplib              tokenize
_pydev_runfiles     distutils           posixpath           trace
_pydevd_bundle      doctest             pprint              traceback
_pydevd_frame_eval  dummy_threading     profile             tracemalloc
_pyio               easy_install        pstats              tty
_random             email               pty                 turtle
_sha1               encodings           py_compile          turtledemo
_sha256             ensurepip           pyclbr              types
_sha3               enum                pycompletionserver  typing
_sha512             errno               pydev_app_engine_debug_startup unicodedata
_signal             faulthandler        pydev_coverage      unittest
_sitebuiltins       filecmp             pydev_ipython       urllib
_socket             fileinput           pydev_pysrc         uu
_sqlite3            fnmatch             pydev_run_in_console uuid
_sre                formatter           pydevconsole        venv
_ssl                fractions           pydevd              warnings
_stat               ftplib              pydevd_concurrency_analyser wave
_string             functools           pydevd_file_utils   weakref
_strptime           gc                  pydevd_plugins      webbrowser
_struct             genericpath         pydoc               winreg
_symtable           getopt              pydoc_data          winsound
_testbuffer         getpass             pyexpat             wsgiref
_testcapi           gettext             queue               xdrlib
_testconsole        glob                quopri              xml
_testimportmultiple gzip                random              xmlrpc
_testmultiphase     hashlib             re                  xxsubtype
_thread             heapq               reprlib             zipapp
_threading_local    hmac                rlcompleter         zipfile
_tkinter            html                runfiles            zipimport
_tracemalloc        http                runpy               zlib
_warnings           idlelib             sched               
_weakref            imaplib             secrets             
_weakrefset         imghdr              select              
Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

2、使用模块的好处?

  • 提高可维护性;
  • 可重用;
  • 避免函数名的冲突;

3、模块的分类;

  • 内置标准模块(又称标准库),可通过执行help(‘modules’)查看所有Python自带的模块列表;
  • 第三方开源模块,可以通过pip install 模块名,联网安装;
  • 自定义模块;

4、模块的调用;

  • import module
  • from module import xx
  • from module.xx.xx import xx as rename
  • from module.xx.xx import *
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/27 0027 10:43
""
"""
格式:
1、import module
2、from module import xx #从哪来,到哪去!
3、from module.xx.xx import xx as rename #起个别名;
4、from module.xx.xx import *  #*代表所有,不建议使用,变量名容易冲突;
"""
import os
import sys
from os import rmdir
from os import rmdir,rename,replace#逗号分隔,导入多个;

模块一旦被调用,即相当于执行了另外一个py文件里的代码;

03-常用模块学习-模块的导入路径

1、模块的导入路径;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/27 0027 11:25
import sys
print(sys.path)
"""
[
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\文件操作&函数\\模块', 
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018', 
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\venv\\Scripts\\python36.zip', 
'C:\\Program Files\\Python36\\DLLs',
'C:\\Program Files\\Python36\\lib', 'C:\\Program Files\\Python36',
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\venv', 
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\venv\\lib\\site-packages',
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\venv\\lib\\site-packages\\setuptools-39.0.1-py3.6.egg', 
'C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\venv\\lib\\site-packages\\pip-9.0.3-py3.6.egg', 
'C:\\Program Files\\JetBrains\\PyCharm 2018.1.3\\helpers\\pycharm_matplotlib_backend'
]
"""
#注意使用转义字符\
#只是一次性有效;
sys.path.append('C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\文件操作&函数\\模块')
print(sys.path)
#import my_modules
#del my_modules
"""
小结:模块查找路径有顺序;
"""

04-常用模块学习-开源模块学习的安装方式

1、开源模块的介绍;

https://pypi.org/ 是python的开源模块库,截止2017年9.30日 ,已经收录了118170个来自全世界python开发者贡献的模块,几乎涵盖了你想用python做的任何事情。 事实上每个python开发者,只要注册一个账号就可以往这个平台上传你自己的模块,这样全世界的开发者都可以容易的下载并使用你的模块。

2、开源模块的安装方法总结;

1)使用源码包进行安装;

下载地址: https://files.pythonhosted.org/packages/c4/22/167ec8e203b0f930582a82a1bfcf7faf9d14af3a0d6abc807dbb22ed52f8/PyTyrion-1.0.1.tar.gz

  • 编译源码 python setup.py build
  • 安装源码 python setup.py install

2)使用pip工具进行安装;

  • pip3 install PyTyrion
  • pip3 uninstall PyTyrion
  • import Tyrion#使用它;

Pytion介绍:https://pypi.org/project/PyTyrion/

05-常用模块学习-使用国内源下载模块

1、pip命令默认会连接在国外的python官方服务器下载,速度比较慢,你还可以使用国内的豆瓣源,数据会定期同步国外官网,速度快好多;

pip install -i http://pypi.douban.com/simple/ alex_sayhi --trusted-host pypi.douban.com #alex_sayhi是模块名,注意alex_sayhi前面有空格;
Microsoft Windows [版本 10.0.16299.15]
(c) 2017 Microsoft Corporation。保留所有权利。

(venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install PyTyrion#安装
Collecting PyTyrion
  Using cached https://files.pythonhosted.org/packages/c4/22/167ec8e203b0f930582a82a1bfcf7faf9d14a
f3a0d6abc807dbb22ed52f8/PyTyrion-1.0.1.tar.gz
Installing collected packages: PyTyrion
  Running setup.py install for PyTyrion ... done Successfully installed PyTyrion-1.0.1 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 uninstall PyTyrion#卸载 Uninstalling PyTyrion-1.0.1: c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\pytyrion-1.0.1-py3.6.egg- info c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__init__.py c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__pycache__\__init __.cpython-36.pyc c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__pycache__\fields .cpython-36.pyc c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__pycache__\forms. cpython-36.pyc c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__pycache__\framew ork.cpython-36.pyc c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\__pycache__\widget .cpython-36.pyc c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\fields.py c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\forms.py c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\framework.py c:\users\administrator\pycharmprojects\lfxc2018\venv\lib\site-packages\tyrion\widget.py Proceed (y/n)? y Successfully uninstalled PyTyrion-1.0.1 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install PyTyrion Collecting PyTyrion Using cached https://files.pythonhosted.org/packages/c4/22/167ec8e203b0f930582a82a1bfcf7faf9d14a f3a0d6abc807dbb22ed52f8/PyTyrion-1.0.1.tar.gz Installing collected packages: PyTyrion Running setup.py install for PyTyrion ... done Successfully installed PyTyrion-1.0.1 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install -i http://pypi.douban.com/simp le/alex_sayhi --trusted-host pypi.douban.com You must give at least one requirement to install (see "pip help install") You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install -i http://pypi.douban.com/simp le/ alex_sayhi --trusted-host pypi.douban.com#注意alex_sayhi前面有一空格; Collecting alex_sayhi Downloading http://pypi.doubanio.com/packages/84/14/b59d93276c86f6ab556cfa7c2d860b742c1611b601cc 4c7743d129b4b52a/alex_sayhi-1.0.0.tar.gz Installing collected packages: alex-sayhi Running setup.py install for alex-sayhi ... done Successfully installed alex-sayhi-1.0.0 You are using pip version 9.0.3, however version 10.0.1 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>
 1 (venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install paramiko
 2 Collecting paramiko
 3   Downloading https://files.pythonhosted.org/packages/3e/db/cb7b6656e0e7387637ce850689084dc0b94b44
 4 df31cc52e5fc5c2c4fd2c1/paramiko-2.4.1-py2.py3-none-any.whl (194kB)
 5     94% |██████████████████████████████▎ | 184kB 313kB/s eta 0:00:0
 6     100% |████████████████████████████████| 194kB 295kB/s
 7 Collecting pynacl>=1.0.1 (from paramiko)
 8   Downloading https://files.pythonhosted.org/packages/35/ae/5cd8eb69f9341ebb4964faac5f5a00589fbf5d
 9 5f02d84a811c6abcc4f882/PyNaCl-1.2.1-cp36-cp36m-win_amd64.whl (165kB)
10     93% |█████████████████████████████▉  | 153kB 626kB/s eta 0:00:01
11     99% |███████████████████████████████▊| 163kB 626kB/s eta 0:00:
12     100% |████████████████████████████████| 174kB 583kB/s
13 Collecting bcrypt>=3.1.3 (from paramiko)
14   Downloading https://files.pythonhosted.org/packages/4b/c0/c0550e4b98e0536d3a8b8753b68aa0d3c03af6
15 54c43a58328d0bf2c06747/bcrypt-3.1.4-cp36-cp36m-win_amd64.whl
16 Collecting cryptography>=1.5 (from paramiko)
17   Downloading https://files.pythonhosted.org/packages/67/62/67faef32908026e816a74b4b97491f8b9ff393
18 d2951820573599c105cc32/cryptography-2.2.2-cp36-cp36m-win_amd64.whl (1.3MB)
19     91% |█████████████████████████████▍  | 1.2MB 1.2MB/s eta 0:00:01
20     92% |█████████████████████████████▋  | 1.2MB 1.2MB/s eta 0:00:01
21     93% |█████████████████████████████▉  | 1.2MB 1.2MB/s eta 0:00:01
22     94% |██████████████████████████████  | 1.2MB 6.5MB/s eta 0:00:01
23     94% |██████████████████████████████▎ | 1.3MB 6.5MB/s eta 0:00:0
24     95% |██████████████████████████████▋ | 1.3MB 6.7MB/s eta 0:00:0
25     96% |██████████████████████████████▉ | 1.3MB 5.6MB/s eta 0:00:0
26     97% |███████████████████████████████ | 1.3MB 6.5MB/s eta 0:00:0
27     97% |███████████████████████████████▎| 1.3MB 6.6MB/s eta 0:00:
28     98% |███████████████████████████████▋| 1.3MB 6.0MB/s eta 0:00:
29     99% |███████████████████████████████▉| 1.3MB 6.4MB/s eta 0:00:
30     100% |████████████████████████████████| 1.3MB 977kB/s
31 Collecting pyasn1>=0.1.7 (from paramiko)
32   Downloading https://files.pythonhosted.org/packages/a0/70/2c27740f08e477499ce19eefe05dbcae6f19fd
33 c49e9e82ce4768be0643b9/pyasn1-0.4.3-py2.py3-none-any.whl (72kB)
34     98% |███████████████████████████████▋| 71kB 8.8MB/s eta 0:00:0
35     100% |████████████████████████████████| 81kB 3.7MB/s
36 Collecting six (from pynacl>=1.0.1->paramiko)
37   Downloading https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca
38 43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
39 Collecting cffi>=1.4.1 (from pynacl>=1.0.1->paramiko)
40   Downloading https://files.pythonhosted.org/packages/2f/85/a9184548ad4261916d08a50d9e272bf6f93c54
41 f3735878fbfc9335efd94b/cffi-1.11.5-cp36-cp36m-win_amd64.whl (166kB)
42     92% |█████████████████████████████▌  | 153kB 6.7MB/s eta 0:00:01
43     98% |███████████████████████████████▍| 163kB 6.5MB/s eta 0:00:
44     100% |████████████████████████████████| 174kB 3.1MB/s
45 Collecting asn1crypto>=0.21.0 (from cryptography>=1.5->paramiko)
46   Downloading https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8
47 ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl (101kB)
48     100% |████████████████████████████████| 102kB 3.5MB/s
49 Collecting idna>=2.1 (from cryptography>=1.5->paramiko)
50   Downloading https://files.pythonhosted.org/packages/27/cc/6dd9a3869f15c2edfab863b992838277279ce9
51 2663d334df9ecf5106f5c6/idna-2.6-py2.py3-none-any.whl (56kB)
52     100% |████████████████████████████████| 61kB 3.5MB/s
53 Collecting pycparser (from cffi>=1.4.1->pynacl>=1.0.1->paramiko)
54   Downloading https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8e91fb81df177adcc20
55 73d36a17b1491fd09df6ed/pycparser-2.18.tar.gz (245kB)
56     91% |█████████████████████████████▎  | 225kB 7.0MB/s eta 0:00:01
57     95% |██████████████████████████████▋ | 235kB 6.8MB/s eta 0:00:0
58     99% |████████████████████████████████| 245kB 6.8MB/s eta 0:00:
59     100% |████████████████████████████████| 256kB 2.7MB/s
60 Installing collected packages: six, pycparser, cffi, pynacl, bcrypt, asn1crypto, idna, cryptograph
61 y, pyasn1, paramiko
62   Running setup.py install for pycparser ... done
63 Successfully installed asn1crypto-0.24.0 bcrypt-3.1.4 cffi-1.11.5 cryptography-2.2.2 idna-2.6 para
64 miko-2.4.1 pyasn1-0.4.3 pycparser-2.18 pynacl-1.2.1 six-1.11.0
65 You are using pip version 9.0.3, however version 10.0.1 is available.
66 You should consider upgrading via the 'python -m pip install --upgrade pip' command.
##########################################################使用国内豆瓣源下载速度对比###########################################

(venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install -i http://pypi.douban.com/simp
le/ paramiko
Collecting paramiko
The repository located at pypi.douban.com is not a trusted or secure host and is being ignored.
If this repository is available via HTTPS it is recommended to use HTTPS instead, otherwise you ma
y silence this warning and allow it anyways with '--trusted-host pypi.douban.com'.
Could not find a version that satisfies the requirement paramiko (from versions: )
No matching distribution found for paramiko
You are using pip version 9.0.3, however version 10.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\Administrator\PycharmProjects\LFXC2018>pip3 install -i http://pypi.douban.com/simp
le/ paramiko --trusted-host pypi.douban.com
Collecting paramiko
Downloading http://pypi.doubanio.com/packages/3e/db/cb7b6656e0e7387637ce850689084dc0b94b44df31cc
52e5fc5c2c4fd2c1/paramiko-2.4.1-py2.py3-none-any.whl (194kB)
94% |██████████████████████████████▎ | 184kB 1.3MB/s eta 0:00:0
100% |████████████████████████████████| 194kB 1.4MB/s
Requirement already satisfied: cryptography>=1.5 in c:\users\administrator\pycharmprojects\lfxc201
8\venv\lib\site-packages (from paramiko)
Requirement already satisfied: bcrypt>=3.1.3 in c:\users\administrator\pycharmprojects\lfxc2018\ve
nv\lib\site-packages (from paramiko)
Requirement already satisfied: pyasn1>=0.1.7 in c:\users\administrator\pycharmprojects\lfxc2018\ve
nv\lib\site-packages (from paramiko)
Requirement already satisfied: pynacl>=1.0.1 in c:\users\administrator\pycharmprojects\lfxc2018\ve
nv\lib\site-packages (from paramiko)
Requirement already satisfied: cffi>=1.7; platform_python_implementation != "PyPy" in c:\users\adm
inistrator\pycharmprojects\lfxc2018\venv\lib\site-packages (from cryptography>=1.5->paramiko)
Requirement already satisfied: idna>=2.1 in c:\users\administrator\pycharmprojects\lfxc2018\venv\l
ib\site-packages (from cryptography>=1.5->paramiko)
Requirement already satisfied: six>=1.4.1 in c:\users\administrator\pycharmprojects\lfxc2018\venv\
lib\site-packages (from cryptography>=1.5->paramiko)
Requirement already satisfied: asn1crypto>=0.21.0 in c:\users\administrator\pycharmprojects\lfxc20
18\venv\lib\site-packages (from cryptography>=1.5->paramiko)
Requirement already satisfied: pycparser in c:\users\administrator\pycharmprojects\lfxc2018\venv\l
ib\site-packages (from cffi>=1.7; platform_python_implementation != "PyPy"->cryptography>=1.5->par
amiko)
Installing collected packages: paramiko
Successfully installed paramiko-2.4.1
You are using pip version 9.0.3, however version 10.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\Administrator\PycharmProjects\LFXC2018>

06-常用模块学习-包及跨模块导入

1、包的概念引入;

.
└── my_proj
    ├── crm #代码目录;此处就是包;
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py
    └── my_proj #配置文件目录;此处也是包;
        ├── settings.py
        ├── urls.py
        └── wsgi.py

当我们的模块文件越来越多,为了容易管理,就需要对模块文件进行划分,比如把负责跟数据库交互的都放一个文件夹,把与页面交互相关的放一个文件夹,其中,一个文件夹管理多个模块文件,这个文件夹就被称为包;

2、不同模块

07-常用模块学习-跨模块导入2

1、绝对路径与相对路径;

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # __Author__:Administrator
 4 # Version:python3.6.5
 5 # Date:2018/5/27 0027 13:51
 6 import sys,os
 7 print(dir())#['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'sys']
 8 print(__file__)#C:/Users/Administrator/PycharmProjects/LFXC2018/文件操作&函数/模块/packages/my_proj/crm/views.py
 9 #BASE_DIR = os.path.dirname(os.path.dirname(__file__))#相对路径;
10 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#绝对路径;abspath
11 print("BASE_DIR",BASE_DIR)
12 sys.path.append(BASE_DIR)
13 #sys.path.append("C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\文件操作&函数\\模块\\packages\\my_proj")
14 print(sys.path)
15 from proj import settings
16 def sayhi():
17     print('Hello World.')
18 #一出手就是专业的!
19 
20 
21 def sayhi():
22     print('hello world!')

08-常用模块学习-相对导入

1、相对导入(使用场景不多);

绝对导入&相对导入
在linux里可以通过cd ..回到上一层目录 ,cd ../.. 往上回2层,这个..就是指相对路径,在python里,导入也可以通过..

例如:

.
├── __init__.py
├── crm
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py  #from ..proj import settings 
├── manage.py   
└── proj
    ├── __init__.py
    ├── settings.py #from .import urls  
    ├── urls.py
    └── wsgi.py
views.py里代码

from ..proj import settings
def sayhi():
    print('hello world!')

print(settings.DATABASES)
执行结果报错了

Traceback (most recent call last):
File "my_proj/crm/views.py", line 4, in <module>
 from ..proj import settings
SystemError: Parent module '' not loaded, cannot perform relative import
或者有人会看到这个错

ValueError: attempted relative import beyond top-level package
其实这两个错误的原因归根结底是一样的:在涉及到相对导入时,package所对应的文件夹必须正确的被python解释器视作package,而不是普通文件夹。否则由于不被视作package,无法利用package之间的嵌套关系实现python中包的相对导入。

文件夹被python解释器视作package需要满足两个条件:

文件夹中必须有__init__.py文件,该文件可以为空,但必须存在该文件。
不能作为顶层模块来执行该文件夹中的py文件(即不能作为主函数的入口)。
所以这个问题的解决办法就是,既然你在views.py里执行了相对导入,那就不要把views.py当作入口程序,可以通过上一级的manage.py调用views.py

.
├── __init__.py
├── crm
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py  #from ..proj import settings 
├── manage.py  #from crm import views 
└── proj
    ├── __init__.py
    ├── settings.py #from .import urls  
    ├── urls.py
    └── wsgi.py
事实证明还是不行,报错

ValueError: attempted relative import beyond top-level package
但把from ..proj import settings 改成from . import models 后却执行成功了,为什么呢?

from .. import models会报错的原因是,这句代码会把manage.py所在的这一层视作package,但实际上它不是,因为package不能是顶层入口代码,若想不出错,只能把manage.py往上再移一层。

正确的代码目录结构如下

    packages/
    ├── __init__.py
    ├── manage.py #from my_proj.crm  import views
    └── my_proj
        ├── crm
        │   ├── admin.py
        │   ├── apps.py
        │   ├── models.py
        │   ├── tests.py
        │   ├── views.py  #from . import models;  from ..proj import settings 
        └── proj
            ├── __init__.py
            ├── settings.py
            ├── urls.py
            └── wsgi.py
再执行manage.py就不会报错了。

注:虽然python支持相对导入,但对模块间的路径关系要求比较严格,处理不当就容易出错,so并不建议在项目里经常使用。

09-常用模块学习-time模块详解

1、time模块初识;

在平常的代码中,我们常常需要与时间打交道。在Python中,与时间处理有关的模块就包括:time,datetime,calendar(很少用,不讲),下面分别来介绍。

在开始之前,首先要说明几点:

一、在Python中,通常有这几种方式来表示时间:

  1. 时间戳;
  2. 格式化的时间字符串;
  3. 元组(struct_time)共九个元素。由于Python的time模块实现主要调用C库,所以各个平台可能有所不同。

二、几个定义

UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时。

时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

元组(struct_time)方式:struct_time元组共有9个元素,返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素:

索引(Index)    属性(Attribute)    值(Values)
0     tm_year(年)                 比如2011 
1     tm_mon(月)             1 - 12
2     tm_mday(日)                 1 - 31
3     tm_hour(时)                 0 - 23
4     tm_min(分)             0 - 59
5     tm_sec(秒)             0 - 61
6     tm_wday(weekday)            0 - 6(0表示周日)
7     tm_yday(一年中的第几天)    1 - 366
8     tm_isdst(是否是夏令时)            默认为-1

time模块的方法

  • time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
  • time.gmtime([secs]):和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
  • time.time():返回当前时间的时间戳。
  • time.mktime(t):将一个struct_time转化为时间戳。
  • time.sleep(secs):线程推迟指定的时间运行。单位为秒。
  • time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:'Sun Oct 1 12:04:38 2017'。如果没有参数,将会将time.localtime()作为参数传入。
  • time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
  • time.strftime(format[, t]):把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。

    • 举例:time.strftime("%Y-%m-%d %X", time.localtime()) #输出'2017-10-01 12:14:23'
  • time.strptime(string[, format]):把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。

    • 举例:time.strptime('2017-10-3 17:54',"%Y-%m-%d %H:%M") #输出 time.struct_time(tm_year=2017, tm_mon=10, tm_mday=3, tm_hour=17, tm_min=54, tm_sec=0, tm_wday=1, tm_yday=276, tm_isdst=-1)
字符串转时间格式对应表
 
  Meaning Notes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
  %% A literal '%'character.

最后为了容易记住转换关系,看下图

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/27 0027 15:24
import time
print("从1970年1月1日00:00:00:00起,返回当前时间的时间戳:",time.time())#从1970年1月1日
print("将一个时间戳转换为当前时区的struct_time:",time.localtime())#time.struct_time(tm_year=2018, tm_mon=5, tm_mday=27, tm_hour=15, tm_min=29, tm_sec=50, tm_wday=6, tm_yday=147, tm_isdst=0)
print("打印当前时区(北京时区)的struct_time:",time.localtime(1527406435.9800334))#将一个时间戳转换为当前时区的stuct_time。
#time.gmtime()和localtime()方法类似,不过gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time

a = time.localtime()
print("打印自定义格式的时间:",'%s-%s-%s'%(a.tm_year,a.tm_mon,a.tm_mday))#2018-5-27
print("打印0时区的struct_time:",time.gmtime())#time.struct_time(tm_year=2018, tm_mon=5, tm_mday=27, tm_hour=7, tm_min=32, tm_sec=35, tm_wday=6, tm_yday=147, tm_isdst=0)
print("将struct_time转换为时间戳显示:",time.mktime(a))#1527407076.0

print("线程推迟指定的是时间运行,就是让'程序'睡一会儿再运行:",time.sleep(1))
print("time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:'Sun Oct 1 12:04:38 2017'。如果没有参数,将会将time.localtime()作为参数传入。",time.asctime())
print(time.ctime())#Sun May 27 15:50:54 2018
print(time.ctime(0))#Thu Jan  1 08:00:00 1970
print(time.ctime(1232123))#Thu Jan 15 14:15:23 1970

#print(help(time.strftime()))
"""
time.strftime(format[, t]):把一个代表时间的元组
或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。
如果t未指定,将传入time.localtime()。
"""
print(time.strftime('2017'))
print(time.strftime('2017-8'))
print(time.strftime('%Y-%m-%d'))#2018-05-27
print(time.strftime('%Y-%m-%d %H:%M:%S'))#2018-05-27 15:58:32
b = time.localtime(1898908909)
print(time.strftime('%Y-%m-%d %H:%M:%S',b))#2030-03-05 10:41:49
print(time.strftime('%Y-%m-%d %H:%M:%S  %U '))#2018-05-27 16:04:38  21
print(time.strftime('%Y-%m-%d %H:%M:%S %w'))#2018-05-27 16:04:38 0
print(time.strftime('%Y-%m-%d %H:%M:%S %z '))#2018-05-27 16:04:38 +0800
print(time.strftime('%Y-%m-%d %H:%M:%S %Z'))#2030-03-05 10:41:49
print("-------------------内容太多了,打个断点吧!--------------")
s = time.strftime('%Y-%m-%d %H:%M:%S')
print(time.strptime(s,'%Y-%m-%d %H:%M:%S'))#与time.strftime('%Y-%m-%d %H:%M:%S')互为逆操作

10-常用模块学习-datetime模块详解

1、datetime模块;

datetime模块

相比于time模块,datetime模块的接口则更直观、更容易调用

datetime模块定义了下面这几个类:

  • datetime.date:表示日期的类。常用的属性有year, month, day;
  • datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond;
  • datetime.datetime:表示日期时间。
  • datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
  • datetime.tzinfo:与时区有关的相关信息。(这里不详细充分讨论该类,感兴趣的童鞋可以参考python手册)

我们需要记住的方法仅以下几个:

  1. d=datetime.datetime.now() 返回当前的datetime日期类型
d.timestamp(),d.today(), d.year,d.timetuple()等方法可以调用

2.datetime.date.fromtimestamp(322222) 把一个时间戳转为datetime日期类型

3.时间运算

>>> datetime.datetime.now()

datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)

>>> datetime.datetime.now() + datetime.timedelta(4) #当前时间 +4天

datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)

>>> datetime.datetime.now() + datetime.timedelta(hours=4) #当前时间+4小时

datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)

4.时间替换

>>> d.replace(year=2999,month=11,day=30)

datetime.date(2999, 11, 30)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/27 0027 16:14
import datetime,time
print(datetime.datetime)#<class 'datetime.datetime'>
print(datetime.datetime.now())#2018-05-27 16:15:02.575789
a = datetime.datetime.now()
print(a)
print(a.year)
print(a.month)
print(a.day)
print(a.hour)
print(a.minute)
print(a.second)
print(a.microsecond)

print(datetime.datetime(2017,10,12,20,8,25,59782))#2017-10-12 20:08:25.059782
print(datetime.date.fromtimestamp(time.time()))#将时间戳快速的转换为“年月日”格式;

d = datetime.date.fromtimestamp(time.time())
print(d.year)#2018
print("打个断点吧!----------------------------------------------")
print(datetime.timedelta(1))#1 day, 0:00:00
print(datetime.datetime.now())#2018-05-27 16:24:18.928623
print("------------------------------")
t = datetime.timedelta(1)
print(datetime.datetime.now() -t)#2018-05-26 16:25:28.727510
print(datetime.datetime.now() - datetime.timedelta(days=3))#2018-05-24 16:25:28.727510
print(datetime.datetime.now() - datetime.timedelta(hours=4))#2018-05-24 12:25:28.727510
print(datetime.datetime.now() + datetime.timedelta(hours=4))#2018-05-24 20:25:28.727510
print(datetime.datetime.now() + datetime.timedelta(minutes=10))#2018-05-24 16:35:28.727510


d=datetime.datetime.now()
print(d)#2018-05-27 16:34:05.117929
print(d.replace(year=2006))#2006-05-27 16:34:38.694003
print(d.replace(year=2006,month=8,day=20,hour=18,minute=45))#2006-08-20 18:45:04.031477

11-常用模块学习-random模块详解

1、随机数random模块初识;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/28 0028 6:25
import random
print("顾头又顾尾:",random.randint(1,100))#78,顾头又顾尾
print("顾头又顾尾:",random.randint(1,3))#3,顾头又顾尾
print("顾头不顾尾:",random.randrange(1,3))#1,顾头不顾尾
print("顾头不顾尾:",random.randrange(1,3))#2,顾头不顾尾
print("顾头不顾尾,随机选取1~100之间的奇数:",random.randrange(1,100,2))#17,顾头不顾尾
print("顾头不顾尾,随机选取0~100之间的偶数:",random.randrange(0,100,2))#28,顾头不顾尾
print("生成随机浮点数:",random.random())#0.31159629694637025
print("返回给定数据集合中的1个随机字符:",random.choice('fdsajkl!#@!@#!1232132'))# 2
print("返回给定数据集合中的N个随机字符:",random.sample('fdsajkl!#@!@#!1232132',3))#['!', 'k', '3']
print(''.join(random.sample('fdsajkl!#@!@#!1232132',8)))#s!j@!k2a

import string
print("生成包含'大小写'的字符串:",string.ascii_letters)#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print("生成只包含'所有大写[A-Z]'的字母字符串:",string.ascii_uppercase)#ABCDEFGHIJKLMNOPQRSTUVWXYZ
print("生成只包含'所有小写[a-z]'的字母字符串:",string.ascii_lowercase)#abcdefghijklmnopqrstuvwxyz
print("生成包含'所有叔子[0-9]'的数字字符串:",string.digits)#0123456789
print(string.ascii_lowercase + string.digits)#abcdefghijklmnopqrstuvwxyz0123456789
print(''.join(random.sample(string.ascii_lowercase + string.digits,6)))#7g8jrs
print("生成特殊字符",string.punctuation)#!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(''.join(random.sample(string.ascii_lowercase + string.digits+string.punctuation,18)))#d4}5c+/m|97e@"16]s

s = string.ascii_lowercase + string.digits+string.punctuation
print("生成15位随机验证码",''.join(random.sample(s,15)))#"%}l#?t,8c{ei/'
d = list(range(0,20))#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
print(d)
random.shuffle(d)#洗牌;
print(d)#[5, 15, 12, 14, 9, 6, 1, 11, 0, 10, 13, 17, 18, 19, 4, 3, 7, 8, 2, 16]
names = ('cxz','cxs','cxl','cql')
print(names)#['cxz', 'cxs', 'cxl', 'cql']
#random.shuffle(names)#洗牌元组
#print(names)#TypeError: 'tuple' object does not support item assignment
s = 'fdsaklfdjsakl;fdsa'
#random.shuffle(s)#
#print(s)#TypeError: 'str' object does not support item assignment
#实际运用场景:将员工的姓名全部放到一个list中,年会的时候就可以用来随机抽奖;

12-常用模块学习-os模块详解

1、通过os模块完成跟操作系统的交互;

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# __Author__:Administrator
# Version:python3.6.5
# Date:2018/5/28 0028 7:08
import os
print("获取当前的工作目录:",os.getcwd())#C:\Users\Administrator\PycharmProjects\LFXC2018\文件操作&函数\模块
#print("返回指定目录下的所有文件和目录名:",os.listdir('指定目录'))
#print("删除指定文件:",os.remove('remov.txt'))
#print("删除指定目录:",os.removedirs('指定目录'))
print("判断是否为文件:",os.path.isfile('isfile.txt'))
print("判断是否为目录:",os.path.isdir('isdir'))
print("判断是否为链接文件(快捷方式):",os.path.islink('my_modules.lnk'))
print("判断是否为绝对路径:",os.path.isabs('C:\\Users\\Administrator\\PycharmProjects\\LFXC2018\\文件操作&函数\\模块\\指定目录'))
print("检验给出的路径是否真实存在:",os.path.exists('C:\\Users\\Administrator\\PycharmProjects\\LFXC2018'))
print("返回一个文件的目录名和文件名:",os.path.split('01-常用模块学习-小鸡汤.py'))
print("分离文件的拓展名:",os.path.splitext('my_modules.lnk'))
print("获取路径名:",os.path.dirname('05-常用模块学习-使用国内源下载模块.py'))
print("获取绝对路径:",os.path.abspath('05-常用模块学习-使用国内源下载模块.py'))
print("运行Shell命令:",os.system('dir'))#DOS命令
#print("运行Shell命令:",os.system('df -h'))#Linux下执行命令正确返回0,不正确返回非0
print("读取操作系统环境变量HOME的值:",os.getenv('HOME'))
print("返回操作系统中所有的环境变量:",os.environ)
print("设置系统环境变量,仅程序运行时有效:",os.environ.setdefault('HOME','xxxx'))
print("给出当前平台使用的行终止符:",os.linesep)# Windows使用'\r\n',Linux and MAC使用'\n'
print("指示我们正在使用的平台:",os.name)
#print("重命名:",os.rename('old.txt','new.txt'))
#print("创建多级目录:",os.makedirs('c:\\d\\e\\ff'))
#print("创建单个目录:",os.mkdir('c:\\a'))
print("获取文件属性:",os.stat('my_modules.lnk'))
#print("修改文件权限与时间戳:",os.chmod())
print("获取文件大小:",os.path.getsize('10-常用模块学习-datetime模块详解.py'))
print("结合目录名与文件名:",os.path.join('new.txt','isdir'))
print("改变工作目录到dirname:",os.chdir('work'))
#print("获取当前终端的大小:",os.get_terminal_size())
#print("杀死进程:",os.kill(10884,signal.SIGKILL))

13-常用模块学习-sys模块详解

14-常用模块学习-shutil模块详解

15-常用模块学习-序列化模块详解

16-常用模块学习-序列化json模块详解

17-常用模块学习-序列化pickle模块详解

18-常用模块学习-序列化shelve模块详解

19-常用模块学习-xml处理模块详解

20-常用模块学习-自动创建xml文档

21-常用模块学习-configparser模块详解_batch

22-常用模块学习-hashlib加密模块详解

23-常用模块学习-subprocess模块详解

24-常用模块学习-subprocess模块详解2

25-常用模块学习-logging模块基础

26-常用模块学习-logging模块进阶

27-常用模块学习-logging日志过滤和日志文件自动截取

28-常用模块学习-re正则表达式讲解

29-常用模块学习-re匹配语法

30-常用模块学习-re正则表达式公式讲解1

31-常用模块学习-re正则表达式公式讲解2

32-常用模块学习-re正则表达式公式讲解3

33-常用模块学习-re正则表达式公式讲解4

34-常用模块学习-re正则表达式公式讲解5

35-常用模块学习-re正则表达式公式讲解6

36-常用模块学习-re正则表达式公式讲解7

37-常用模块学习-软件开发目录规范

39-常用模块学习-作业需求

猜你喜欢

转载自www.cnblogs.com/tqtl911/p/9095195.html
今日推荐