Python Study Day4 module

Source: Internet
Author: User

module, which implements a set of code for a function with a mound code.   Like functional programming and process-oriented programming, functional programming accomplishes a function, and other code is used to invoke it, providing reusability of code and coupling between code. For a complex function, multiple functions may be required to complete (functions can also be in different. py files), and the code set consisting of n  .py  files is called a module. such as:os  is a system-related module; file is a document operation related module module is divided into three kinds: custom module built-in module open source module Custom Module 1, the definition module to write its own module file 2, import module import modulefrom  Module.xx.xx import xxfrom module.xx.xx import xx as rename  from  module.xx.xx import * the module is imported according to that path as a benchmark? That is:sys.pathimport sysprint sys.path   result: ['/users/wupeiqi/pycharmprojects/calculator/p1/pp1 ' ,  '/usr/local/lib/python2.7/site-packages/setuptools-15.2-py2.7.egg ',  '/usr/local/lib/python2.7/ Site-packages/distribute-0.6.28-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/mysql_ Python-1.2.4b4-py2.7-macosx-10.10-x86_64.egg ',  '/usr/local/lib/python2.7/site-packages/ Xlutils-1.7.1-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/xlwt-1.0.0-py2.7.egg ',  '/usr/local /lib/python2.7/site-packages/xlrd-0.9.3-py2.7.egg ',   ' /usr/local/lib/python2.7/site-packages/tornado-4.1-py2.7-macosx-10.10-x86_64.egg ',  '/usr/local/lib/ Python2.7/site-packages/backports.ssl_match_hostname-3.4.0.2-py2.7.egg ',  '/usr/local/lib/python2.7/ Site-packages/certifi-2015.4.28-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/ Pyopenssl-0.15.1-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/six-1.9.0-py2.7.egg ',  '/usr/ Local/lib/python2.7/site-packages/cryptography-0.9.1-py2.7-macosx-10.10-x86_64.egg ',  '/usr/local/lib/ Python2.7/site-packages/cffi-1.1.1-py2.7-macosx-10.10-x86_64.egg ',  '/usr/local/lib/python2.7/ Site-packages/ipaddress-1.0.7-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/enum34-1.0.4-py2.7.egg ' ,  '/usr/local/lib/python2.7/site-packages/pyasn1-0.1.7-py2.7.egg ',  '/usr/local/lib/python2.7/ Site-packages/idna-2.0-py2.7.egg ',  '/usr/local/lib/python2.7/site-packages/pycparser-2.13-py2.7.egg ',   '/usr/local/lib/python2.7/site-packages/django-1.7.8-py2.7.egg',  '/usr/local/lib/python2.7/site-packages/paramiko-1.10.1-py2.7.egg ',  '/usr/local/lib/python2.7/ Site-packages/gevent-1.0.2-py2.7-macosx-10.10-x86_64.egg ',  '/usr/local/lib/python2.7/site-packages/ Greenlet-0.4.7-py2.7-macosx-10.10-x86_64.egg ',  '/users/wupeiqi/pycharmprojects/calculator ',  '/usr/ Local/cellar/python/2.7.9/frameworks/python.framework/versions/2.7/lib/python27.zip ',  '/usr/local/Cellar/ python/2.7.9/frameworks/python.framework/versions/2.7/lib/python2.7 ',  '/usr/local/cellar/python/2.7.9/ Frameworks/python.framework/versions/2.7/lib/python2.7/plat-darwin ',  '/usr/local/cellar/python/2.7.9/ Frameworks/python.framework/versions/2.7/lib/python2.7/plat-mac ',  '/usr/local/cellar/python/2.7.9/ Frameworks/python.framework/versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages ',  '/usr/local/Cellar/ Python/2.7.9/frameworks/python.framework/versions/2.7/lib/python2.7/lib-tk ',  '/usr/local/Cellar/python/ 2.7.9/frameworks/python.framework/versIons/2.7/lib/python2.7/lib-old ',  '/usr/local/cellar/python/2.7.9/frameworks/python.framework/versions/2.7 /lib/python2.7/lib-dynload ',  '/usr/local/lib/python2.7/site-packages ',  '/Library/Python/2.7/ Site-packages '] If the Sys.path path list does not have the path you want, it can be added by  sys.path.append (' path ')  . Various directories can be obtained through the OS module, for example: Import sysimport ospre_path = os.path.abspath ('.. /') Sys.path.append (pre_path) Open source module One, download installs the download installs two kinds of ways: Yum pipeasy-installapt-get Download the source code to extract source code to enter the directory compiles the source code      python setup.py build installation Source     python setup.py  Install in the use of source installation, you need to use to the GCC compilation and Python development environment, so you need to first execute:yum install gccyum install  After the installation of Python-devel or Apt-get python-dev is successful, the module is automatically installed in a directory in  sys.path , such as:/usr/lib/python2.7/ Site-packages/Module Introduction  paramikoparamiko is a module for remote control, using the module can be used to command or file the remote server, it is worth saying that The remote management of fabric and ansible is the use of Paramiko to reality. 1, download installs the # pycrypto, because the  paramiko  module internal dependence Pycrypto, therefore installs the installation pycrypto#  download installs first  PYCRYPTOWGET http://files.cnblogs.com/files/wupeiqi/pycrypto-2.6.1.tar.gztar -xvf pycrypto-2.6.1.tar.gzcd  pycrypto-2.6.1python setup.py buildpython setup.py install #  into the Python environment, Import crypto Check for installation success  #  download installation  paramikowget http://files.cnblogs.com/files/wupeiqi/ paramiko-1.10.1.tar.gztar -xvf paramiko-1.10.1.tar.gzcd paramiko-1.10.1python setup.py  buildpython setup.py install #  Enter the python environment, import Paramiko Check if the installation is successful 2, use module execution Instructions #!/usr/bin/env  python#coding:utf-8import paramikossh = paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) ssh.connect (' 192.168.1.108 ', 22,  ' Eddy ',  ' 123 ') Stdin, stdout, stderr  = ssh.exec_command (' DF ') Print stdout.read () ssh.close (), upload, download via password import os,sysimport  Paramikot = paramiko. Transport (' 182.92.219.86 ', ()) T.connect (Username= ' Eddy ', password= ' 123 ') Sftp = paramiko. SFtpclient.from_transport (t) sftp.put ('/tmp/test.py ', '/tmp/test.py ')  t.close () Import os,sysimport  paramikot = paramiko. Transport (' 182.92.219.86 ', ()) T.connect (Username= ' Eddy ', password= ' 123 ') Sftp = paramiko. Sftpclient.from_transport (t) sftp.get ('/tmp/test.py ', '/tmp/test2.py ') t.close () upload, download via key import  paramikopravie_key_path =  '/home/auto/.ssh/id_rsa ' Key = paramiko. Rsakey.from_private_key_file (Pravie_key_path) T = paramiko. Transport (' 182.92.219.86 ', ()) T.connect (Username= ' Eddy ', Pkey=key) Sftp = paramiko. Sftpclient.from_transport (t) sftp.put ('/tmp/test3.py ', '/tmp/test3.py ')  t.close () Import paramikopravie _key_path =  '/home/auto/.ssh/id_rsa ' Key = paramiko. Rsakey.from_private_key_file (Pravie_key_path) T = paramiko. Transport (' 182.92.219.86 ', ()) T.connect (Username= ' Eddy ', Pkey=key) Sftp = paramiko. Sftpclient.from_transport (t) sftp.get ('/tmp/test3.py ', '/tmp/test4.py ')  t. Close () built-in module one, OSOS.GETCWD ()   Gets the current working directory, which is the directory path of the current Python script work os.chdir ("DirName")    changes the current script working directory The equivalent of Shell cdos.curdir   returns the current directory:  ('. ') os.pardir   Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ')      can generate multi-level recursive directory Os.removedirs (' dirname1 ')       If the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' dirname ')      generate a single-level directory, equivalent to the shell mkdir  Dirnameos.rmdir (' dirname ')      Delete single-level empty directory, if the directory is not empty can not be deleted, error; equivalent to Rmdir dirnameos.listdir in the shell (' dirname ')      list all files and subdirectories under the specified directory, including hidden files, and print os.remove ()    Delete a file Os.rename (" Oldname "," NewName ")    Rename File/directory Os.stat (' path/filename ')    get File/directory information os.sep      Output operating system-specific path delimiter, win under "\ \", Linux for "/" os.linesep     output the current platform using the line terminator, win under "\t\n", Linux "\ N "os.pathsep     output string to split file path os.name     output string indicates the current usage platform. Win-> ' nt '; linux-> ' POSIX ' Os.system ("bash cOmmand ")    run shell command, direct display os.environ   get system environment variable Os.path.abspath (path)    Return path normalized absolute path Os.path.split (path)    partition path into directory and file name two tuples return os.path.dirname (path)    directory to return path. It is actually the first element of Os.path.split (path)    returns the last file name of path. If path ends with a/or \, then a null value is returned. The second element of Os.path.split (path)    returns true if path exists, or Falseos.path.isabs (path) If path does not exist.    If path is an absolute path, return Trueos.path.isfile (path)    True if path is an existing file. Otherwise, return Falseos.path.isdir (path)    True if path is an existing directory. Otherwise return Falseos.path.join (path1[, path2[,  ...])    returns a combination of multiple paths, the parameters before the first absolute path are ignored Os.path.getatime (path)    Returns the last access time of the file or directory pointed to by Path Os.path.getmtime (path)    returns the last modified time of the file or directory pointed to by path two, syssys.argv             command Line Parameters list, the first element is the program itself path Sys.exit (n)           exit procedure, exit normally (0) Sys.version         Gets the version information of the Python interpreter sys.maxint          the largest int value sys.maxunicode       Maximum Unicode value sys.path            Returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing sys.platform        Returns the operating system platform name Sys.stdout.write (' please: ') val = sys.stdin.readline () [:-1] Three, hashlib import  Md5hash = md5.new () hash.update (' admin ') print hash.hexdigest ()   import  HASHLIBHASH = HASHLIB.MD5 () hash.update (' admin ') print hash.hexdigest () IV, json  and   Pickle two modules for serialization #!/usr/bin/env python# #import  pickledata = {' K1 ': 123, ' K2 ': ' Hello '}p_str  = pickle.dumps (data) print p_str,with open (' Result.pickle ', ' W ')  as fp:     pickle.dump (DATA,FP) import jsonj_str = json.dumps (data) Print j_strwith  open (' Result.json ', ' W ')  as fp:   &nThe Bsp;json.dump (DATA,FP)      Five, rere modules are used for the operation of regular expressions on python. Characters: .  matches any character except newline characters \w match letters or numbers or underscores or Chinese characters \s match any white space character \d match the beginning or end of the word ^ match string end of the match string: \b Repeats 0 or more times + Repeat one or more times, repeat 0 or more times {n} repeats n times {n,} repeats n or more times {n,m} repeats n to M times ip:^ (25[0-5]|2[0-4]\d|[ 0-1]?\d?\d) (\. ( 25[0-5]|2[0-4]\d| [0-1]?\d?\d) {3}$     mobile phone number: ^1[3|4|5|8][0-9]\d{8}$1, Match (pattern, string, flags=0) Starting from the start position matches the specified content according to the model, matching the string flags to match a single regular expression to control how the regular expression is matched import reobj = re.match (' \d+ ',  ' 123uuasf ') If obj:           print obj.group () 123       # flagsi = ignorecase = sre_compile. Sre_flag_ignorecase # ignore casel = locale = sre_compile. Sre_flag_locale # assume current 8-bit localeu = unicode = sre_ Compile. Sre_flag_unicode # assume unicode&nBsp;localem = multiline = sre_compile. sre_flag_multiline # make anchors look for newlines = dotall =  sre_compile. Sre_flag_dotall # make dot match newlinex = verbose = sre_compile . Sre_flag_verbose # ignore whitespace and comments2, Search (pattern, string,  flags=0) matches the specified content according to the Model de-string, matching a single import reobj = re.search (' \d+ ',  ' u123uu888asf ') If obj:         print obj.group ()  123    3, Group and groupsa =  "123abc456" Print re.search ("([0-9]*) ([a-z]*] ([0-9]*)",  a). Group () 123abc456print re.search ("([0-9]*) ([a-z]*] ([0-9]*)",  a). Group (0) 123abc456print re.search ("([0-9 ]*) ([a-z]*) ([0-9]*),  a). Group (1) 123print re.search ("([0-9]*) ([a-z]*] ([0-9]*)",  a). Group (2) Abcprint re.search ("([0-9]*) ([a-z]*] ([0-9]*)",  a). Groups (  (' 123 ',  ' abc ',  ' 456 ') 4, FindAll (pattern, string, flags=0) Both of the above methods are used to match single values, i.e. only one of the strings can be matched , if you want to match all the eligible elements in the string, you need to use  findall import reobj = re.findall (' \d+ ',  ' fa123uu888asf ') print obj [' 123 ',  ' 888 '] 5, sub (pattern, repl, string, count=0,  flags=0) is used to replace the matching string  content =  "123abc456" new_content = re.sub (' \d+ ',  ' SB ',  content) # new_content = re.sub (' \d+ ',  ' SB ',  content, 1) print new_ CONTENTSBABCSB SBABC456 is more powerful than Str.replace  6, split (pattern, string, maxsplit=0,  flags=0) is grouped according to the specified match   content =  ' 1 - 2 *  ((60-30+1* (9-2*5/3+7/3*99/4* 2998+10*568/14)-( -4*3)/(16-3*2)  ) ' "New_content = re.split (' \* ',  content) # new_ Content = re.split (' \* ',  content, 1) print new_content["' 1 - 2 ",  '   (60-30+1 ',  ' (9-2 ',  ' 5/3+7/3 ',  ' 99/4 ',  ' 2998+10 ',  ' 568/14 ')-( -4 ',  ' 3)/(16-3 ',  "2)  ) '" ["' 1 - 2   ", "   ((60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)  ) ']content =   "' 1 - 2 *  ((60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)  ) '" New_ Content = re.split (' [\+\-\*\/]+ ',  content) # new_content = re.split (' \* ',  content, 1) print new_content["' 1 ",  '  2  ',  '   (',  ',  ' 1 ',  ' (9 ',  ' 2 ',  ' 5 ',  ' 3 ',  ' 7 ',  ' 3 ',  ' ',  ' 4 ',  ' 2998 ',  ' 10 ',   ' 568 ',  ') ',  ' (',  ' 4 ',  ' 3) ',  ' (+ ',  ' 3 ',  "2)  ) '" ["' 1 ",    2 *  ((60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14)-( -4*3)/(16-3*2)  ) ']inpp =   ' 1-2* ((60-30 + ( -40-5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ))  -  ( -4*3)/  (16-3*2)) ' Inpp = re.sub (' \s* ', ', INPP) new_content = re.split (' \ ([\+\-\*\/]?\d+[\+\-\*\/ ]?\d+) {1}\) ',  inpp, 1) print new_content

Python Study Day4 module

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.