Execute system command

Source: Internet
Author: User
Tags ftp file timestamp to date

Execute system command
    • Os.system
    • os.spawn*
    • Os.popen
    • popen2.*
    • commands.*

The next three deprecated, the functions of the related modules and functions executing the shell commands are implemented in the Subprocess module and provide richer functionality

Pager

Executes the command, returning the status code.

Import= Subprocess.call (["ls","-L"],shell= False) Print  = Subprocess.call ("ls-l", shell=True)print Ret2

Shell = True, allowing shell commands to be in string form (using the system's own shell)

Shutil

Advanced files, folders, Compression pack processing modules

Shutil.copyfileobj (Fsrc,fdst,length)
Copy the contents of the file to another file, length is the number of copies per read
Import shutils = open (' test1.py ') d = open (' test7.py ', ' WB ') #d. Write (S.read ()) Shutil.copyfileobj (s,d)
Shutil.copyfile (SRC,DST)
Copy files

Import shutilshutil.copyfile ('test1.py','test7.py')

Copy permissions, content group users are unchanged

Shutil.copymode (SRC, DST)

Create a compressed package and return the file path

Shutil.make_archive (Base_name,format ...)

    • Base_name: The file name of the compressed package, or the path of the compressed package, when it is just the file name, is saved in the current directory, otherwise saved to the specified path
    • Format: the kind of compressed package zip tar Batar gztar
    • Root_dir: Folder path to compress, default is current directory

Instance

ImportShutil#Place the/user/local/ftp file www package in the current program directoryret = shutil.make_archive ("www",'Tar', root_dir='/user/local/ftp')#Place the/user/local/ftp file www package in the/user/local directoryRet2 = Shutil.make_archive ("/user/loca/www",'Tar', root_dir='/user/local/ftp')

Shutil Processing of compressed packets is done by calling the ZipFile and tarfile two modules

Import zipfile# Compression z = zipfile. ZipFile (' Ll.zip ', ' W ') z.write (' test1.py ') z.write (' test2.py ') Z.close () # Unzip j = ZipFile. ZipFile (' Ll.zip ', ' R ') J.extractall () J.close ()

Import tarfile# Compressed tar = Tarfile.open (' Y.tar ', ' W ') tar.add ('/usr/local/1.zip ', arcname= ' 1.zip ') tar.add ('/USR/LOCAL/2. Zip ', arcname= ' 2.zip ') Tar.close () # Unzip tar = Tarfile.open (' Y.tar ', ' R ') Tar.extractall () Tar.close ()

Configparser

Used to operate on a specific configuration, the name of the current module is changed to Configparser in the python3.x version

The #!/usr/bin/env python# coding:utf-8# is used to operate on a specific configuration, and the name of the current module is changed to Configparser in the Python 3.x version. Import configparserconfig = Configparser.configparser () config.read (' Goods.txt ') ######### #读操作 ####### Gets the name of the module secs = Config.sections () Print secs# result: [' section1 ', ' Section2 ']# gets the key value of the specified module options = config.options (' Section1 ') print options# result: [' K1 ', ' K2 ']# get itemsitem_list = Config.items (' Section1 ') print item_list# result under the specified module: [(' K1 ', ' v1 '), (' K2 ', ' v2 ') ')]# gets the value of the key under the specified module val = config.get (' Section1 ', ' K2 ') print val######## #写操作 ############# Delete a section module SEC = Config.remove_section (' car ') config.write (open (' I.txt ', ' W ')) # Add the section module. See if a section exists; add sec = config.has_section (' car1 ') print sec # False: Indicates that there is no sec = config.add_section (' car1 ') sec = Config.has_section (' car1 ') print sec # True: Indicates that there is no config.write (open (' I.txt ', ' W ')) # Add seection below Key-valueconfig.set ( ' Car ', ' K1 ', 111111111) config.write (open (' 1.txt ', ' W ')) # Remove the key value below the section for Baomaconfig.remove_option (' car ', ' baoma ') Config.write (Open (' 1.txt ', "w"))

Logging

Module for easy logging and thread-safe

#!/usr/bin/env python# coding:utf-8import logginglogging.basicconfig (filename= ' 1.log ',                    format= '% (asctime) s-% ( Name) s-% (levelname) s-% (module) s-% (message) s ',                    datefmt= '%y-%m-%d%h:%m:%s%p ',                    # level=logging. CRITICAL,                    level=40,                    ) logging.debug (' Debugdebugdebugdebugdebug ') logging.info (' Infoinfoinfoinfoinfoinfoinfo ') logging.warning (' warningwarningwarningwarning ') logging.error (' Errorerrorerrorerrorerrorerror ') logging.critical (' criticalcriticalcriticalcritical ') logging.log (' ASDFGHJKL ') )

Interpretation:

1:filename Create a log file, and then receive it in an additional way

2:format format: Time-user-log level-which module's log-log information

3: Time format: 2015-12-09 11:00:28 AM

4: Log level: You can use numbers, or you can specify directly

Log Level Correspondence table:

CRITICAL = 50

ERROR = 40

WARNING = 30

INFO = 20

DEBUG = 10

#!/usr/bin/env python# coding:utf-8import logginglogging.basicconfig (filename= ' 1.log ',                    format= '% (asctime) s-% ( Name) s-% (levelname) s-% (module) s-% (message) s ',                    datefmt= '%y-%m-%d%h:%m:%s%p ',                    # level=logging. CRITICAL,                    level=logging. DEBUG,                    ) while True:    option = Raw_input ("Enter Number")    if Option.isdigit ():        print "is number", option        Logging.info (' Children enter numbers ')    else:        logging.error (' child, you are not stupid ')

Results:

2015-12-09 13:23:39 pm-root-error-test8-Child, you're not stupid
2015-12-09 13:24:30 pm-root-error-test8-Child, you're not stupid
2015-12-09 13:24:31 Pm-root-info-test8-The child entered a number
2015-12-09 13:24:42 Pm-root-info-test8-The child entered a number

Time datetime

Time-related operations

There are three ways to express time:

      • Timestamp seconds after January 1, 1970 Time.time ()

      • Formatted string 2015-12-12 12:12

      • Structured time tuples include: year, month, day, week, etc. time.struct_time time.localtime ()

    #!/usr/bin/env python# coding:utf-8import timeimport datetimeprint time.time () # 1449631804.64print time.strftime ('% y-%m-%d%h-%m-%s%p ') # default is the current time 2015-12-09 11-04-30 amprint time.localtime () # time.struct_time (tm_year=2015, tm_mon=12, Tm_mday=9, tm_hour=11, tm_min=31, tm_sec=55, tm_wday=2, tm_yday=343, tm_isdst=0) print time.strptime (' 2014-11-11 ', '%Y- %m-%d ') # Convert formatted time to structured time # date to timestamp conversion t = datetime.datetime (2015,11,14,14,14) print type (' t ') # <type ' str ' >ti = Time.mktime (T.timetuple ()) Print Ti # 1447481640.0# timestamp to date conversion TT = Time.localtime () Print tttimestr = Time.strftime ('%y-% m-%d%h:%m:%s ') print timestr# 2015-12-09 13:53:23 

    Re

    The RE module is the operation of a regular expression for Python

    Character:

        1. . Match any characters that are unexpected except for line breaks

        2. \w match letters or numbers or underscores or kanji

        3. \s matches any whitespace character

        4. \d Matching numbers

        5. \b Match the beginning or end of a word

        6. ^ Start of matching string

        7. $ match End of string

      Number:
        1. * Repeat 0 or more times

        2. + Repeat one or more times

        3. ? Repeat 0 or one time

        4. {n} repeats n times

        5. {n,} repeats n or more times

        6. {N,m} repeats n to M times

      1:match (pattern,string,flahs=0)

          Matches the specified content from the starting position based on the model to the string, matching a single

          • Regular expressions

          • The string to match

          • Flag bit, used to control how regular expressions are matched

        Import= Re.match ('\d+','213dsfa32134')  print obj  #  <_sre. Sre_match object at 0x0201ea30>print#  213

        2:search (pattern,string,flahs=0)

        Matches the specified content in a string to match a single

        Import= Re.search ('\d+','213dsfa32134')  print obj  #  <_sre. Sre_match object at 0x0201ea30>print#  213

        3:group and Groups

        Returns one or more subgroups. Returns a substring if the argument is one, and returns a tuple of multiple substrings if there are multiple arguments

        ImportRea="4321fdsa4132"PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Group ()PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Group (0)PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Group (1)PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Group (2)PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Group (3)PrintRe.search ("([0-9]*) ([a-z]*) ([ 0-9]*)", a). Groups ()

        Results:

        4321fdsa4132

        4321fdsa4132

        4321

        Fdsa

        4132

        (' 4321 ', ' fdsa ', ' 4132 ')

        4:findall (pattern,string,flahs=0)

        Match and search can only match one of the strings, and if you want to match all the eligible elements in the string, you need to use the FindAll

        Import"4321fd2sa4132"print re.findall ("\d+ ", a)

        Results:

        [' 4321 ', ' 2 ', ' 4132 ']

        5:sub (pattern,repl,string,count=0,flag=0)
        Used to replace a matching string
        Import"32gbj4321hbj45321"= re.sub ('\d+') ,'+ +', c)print New_c
        Results:
        +++gbj+++hbj+++

        6:split (pattern,string,maxsplit=0,flags=0)

        Grouping according to a specified match

        Importrecontent="' 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)Printnew_content#[' ' 1-2 ', ' ((60-30+1 ', ' (9-2 ', ' 5/3+7/3 ', ' 99/4 ', ' 2998+10 ', ' 568/14 ')-( -4 ', ' 3 ')/(16-3 ', ' 2 ') ' "]New_content1= Re.split ('[\+\-\*\/]+', content)PrintNew_content1#["' 1", ' 2 ', ' ((60 ', ' 30 ', ' 1 ', ' (9 ', ' 2 ', ' 5 ', ' 3 ', ' 7 ', ' 3 ', ' 99 ', ' 4 ', ' 2998 ', ' 10 ', ' 568 ', ' 14 ') ', ' (', ' 4 ', ' 3) ', ' (+ ', ' 3 ', ' 2 ') ']A ="' 1-2 * ((60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)) '"new_a= Re.sub ('\s*',"', a)Printnew_a#' 1-2* ((60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14))-( -4*3)/(16-3*2)) 'New_1 = Re.split ('\ (([\+\-\*\/]?\d+[\+\-\*\/]?\d+) \)', new_a,1)Printnew_1#["' 1-2* (60-30+1* (9-2*5/3+7/3*99/4*2998+10*568/14)-", ' -4*3 ', "/(16-3*2)) ']

        Random

        Random number

        It automatically generates a four-digit alphanumeric combination of strings

        Import" for" in range (4):    =  random.randrange (0,4)     if current! = I        :=  chr (random.randint (65,90)    )Else :         = Random.randint (0,9)    + = Str (temp)print Checkcode

        Execute system commands

        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.