Chapter VI Common module (8): python common module (module execute system commands: subprocess module)

Function: operating system's command execution via python. (Os.system os module () has a similar function)

Tips premise:
the operating system, memory data between two application processes are generally not directly accessible to each other (security system).
Python commands executed on the system, is the equivalent of opening a new process using python, and then execute the command in the new system in the process.
Thus, the implementation of the results because the data is not in the process of python, can not get a normal result.
But subprocess module provides a method to obtain the results of the command system (subprocess.PIPE). So that we can get the results.

Since there is, then what do we do with the subprocess it?
python, washed with subprocess replace in this column below the old modules and methods.
Os.system +
+ os.spawn *

Main methods:

  1. subprocess.run (* popenargs, input = None , timeout = None, check = False, ** kwargs) execute a system command, and waits until the end of execution code proceeds back. Returns the command object execution results. Example:
    `` `Python
    Import The subprocess

    # General command written: input command list
    res1 = subprocess.run ([ 'ipconfig' , '/ all'], stderr = subprocess.PIPE, stdout = subprocess.PIPE, check = True) # command lists into different spaces element
    # execute 'ipconfig / all', the results being given the assignment to stderr, the normal execution assigns the result to stdout, check = True said that if the results of error, which is also being given command line python

    # Get reverse the result of
    print (res1.stdout) # output, when the type of bytes.
    print (res1.stdout.decode ( 'shift-jis ')) # of bytes required for decode (). decode encoding requires a default encoding system (the system is so Japanese shift-jis)

    print (res1.stderr) # outputs given content (yes is null), the type is bytes

    # Involves the pipe symbol '|' command needs to write: Do not use a list, and add the Option: shell = True
    RES2 = subprocess.run ( 'df -h | grep disk1', stderr = subprocess.PIPE, stdout = subprocess.PIPE, shell = True) # shell = True means that command execution taken directly to the system, do not need the list.
    `` `

  2. subprocess.call (* popenargs, timeout = None , ** kwargs)
    similar with the run (), is another way. You need to know what documents can be queried.

  3. subprocess.Popen ()
    to open a new process, execute the command in the background.
    run (), and call () are essentially encapsulates Popen (). It functions are implemented, it is very important!
    Common parameters:
    • args: system commands (linux, Unix: shell; Windows: dos command), it may be a string or sequence type (list, tuple)
    • stdin, stdout, stderr: procedures are standard input, standard output, error
    • preexec_fn: valid only in Unix platform, is used to specify an executable objects (callable object - python functions), he will be called before the child process run
    • shell: In the run () is described in Example
    • cwd: the amount used to set the current directory of the child process
    • env: used to specify the child process environment variables. If env = None, environment variables child process inherited from the parent process.
      Think of the difference between the following two commands:
    import subprocess
    
    a = subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)  # 等待系统命令执行完后继续
    b = subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)  # 打开一个新进程,在后台执行系统命令
  4. .poll () to check whether the end of the child process, the end of the return return code. (Normal end return 0)

  5. .wait () waits for the child process to finish, and so ended the return return code

  6. .terminate () to terminate the process python program started. With SIGTERM to stop, not mandatory end. Corresponds os.kill (pid, 'SIGTERM')
    python import os import signal os.kill(pid, signal.SIGTERM)

  7. kill () kill the process initiated. Cpu command to interrupt the process. With SIGKILL, terminates the process. Equivalent:
    `` `Python
    Import os
    Import Signal

    os.kill(pid, signal.SIGKILL)
    ```

  8. communicate () to start the process (run () or Popen () process execution) interaction to send data to stdin, and accept the output from stdout, and then wait for the end of the task.

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11110885.html