Examples of some of the manipulation methods of the python process class subprocess

  • 2020-04-02 14:23:35
  • OfStack

Subprocess.popen is used to create child processes.

1) Popen starts a new process and executes in parallel with the parent process. By default, the parent process does not wait for the new process to finish.


def TestPopen():
  import subprocess
  p=subprocess.Popen("dir",shell=True)
  for i in range(250) :
    print ("other things")

2) the p.whait function makes the parent process wait for the newly created process to finish running, and then continue with other tasks of the parent process. At this point, you can get the return value of the new process in p.r.turncode.


def TestWait():
  import subprocess
  import datetime
  print (datetime.datetime.now())
  p=subprocess.Popen("sleep 10",shell=True)
  p.wait()
  print (p.returncode)
  print (datetime.datetime.now())

3) the p.oll function can be used to detect whether the newly created process has ended.


def TestPoll():
  import subprocess
  import datetime
  import time
  print (datetime.datetime.now())
  p=subprocess.Popen("sleep 10",shell=True)
  t = 1
  while(t <= 5):
    time.sleep(1)
    p.poll()
    print (p.returncode)
    t+=1
  print (datetime.datetime.now())

4) p.ill or p.terminate is used to end the new process created, which is equivalent to TerminateProcess() on Windows system and SIGTERM and SIGKILL on posix system.


def TestKillAndTerminate():
    p=subprocess.Popen("notepad.exe")
    t = 1
    while(t <= 5):
      time.sleep(1)
      t +=1
    p.kill()
    #p.terminate()
    print ("new process was killed")

5) p.com munprivate can interact with the new process, but must redirect the pipeline when popen is constructed.


def TestCommunicate():
  import subprocess
  cmd = "dir"
  p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  (stdoutdata, stderrdata) = p.communicate()
 
  if p.returncode != 0:
        print (cmd + "error !")
  #defaultly the return stdoutdata is bytes, need convert to str and utf8
  for r in str(stdoutdata,encoding='utf8' ).split("n"):
    print (r)
  print (p.returncode)
def TestCommunicate2():
  import subprocess
  cmd = "dir"
  #universal_newlines=True, it means by text way to open stdout and stderr
  p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  curline = p.stdout.readline()   while(curline != ""):
        print (curline)
        curline = p.stdout.readline()
  p.wait()
  print (p.returncode)

6) the call function can be considered as a partition of popen and wait, directly passing the command line to be executed to the call function, and returning the exit code of the command line.


def TestCall():
  retcode = subprocess.call("c:\test.bat")
  print (retcode)

7) subprocess. Getoutput and subprocess. Getstatusoutput, basically equivalent to the subprocess. The call function, but can return to the output, or return to the exit code and the output at the same time.

But it is a pity if cannot be used in the Windows platform, on Windows has the following error: '{' is not recognized as an internal or external command, operable program or batch file.


def TestGetOutput():
  outp = subprocess.getoutput("ls -la")
  print (outp) def TestGetStatusOutput():
  (status, outp) = subprocess.getstatusoutput('ls -la')
  print (status)
  print (outp)

8) summary

Popen's arguments, the first of which is a string (or more than one unnamed argument), represent the command you want to execute and the arguments to the command; The following are named parameters; Shell =True, means that your previous command will be executed under the shell, if your command is an executable file or bat, do not need to specify this parameter; Stdout = subprocess.pipe is used to redirect the output of the new process, stderr= subprocess.stdout redirects the error output of the new process to stdout, and stdin= subprocess.pipe is used to redirect the input of the new process; Universal_newlines =True means that stdout and stderr are opened as text.

  Other modules not recommended:

OS. The system
OS. Spawn *
OS. Popen *
Popen2. *
Commands. *


Related articles: