stdout, stderr, stdpipe, and Popen.comunicate () understood

Popen method:

Popen.poll()

  For checking whether the child process has ended. Settings and return returncode property.

Popen.wait()

  Wait for the child process ends. Settings and return returncode property.

Popen.communicate(input=None)

  Interact with the child. Transmitting data to the stdin, stdout and read data from, or to stderr. Optional parameter specifies the input parameter sent to the child process. Communicate () returns a tuple: (stdoutdata, stderrdata). Note: If you want to send data, when creating Popen objects, parameters must be set to stdin stdin PIPE through the process. Similarly, if you want to get data from stdout and stderr, stdout and stderr must be set to PIPE.

Popen.send_signal(signal)

  Send a signal to the child process.

Popen.terminate()

  Stop (stop) the child process. In windows platform, which calls the Windows API TerminateProcess () to end the child process.

Popen.kill()

  Kill the child process.

On Popen.stdin, Popen.stdout, Popen.stderr, official documents say:

stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

Popen.pid

  Get child process's ID.

Popen.returncode

  Process of obtaining the return value. If the process is not over, return None.
=====================================

Stdout and stderr separately

p=subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

(stdoutput,erroutput) = p.communicate()

 

 

It can also be combined, just to stderr parameter is set to subprocess.STDOUT on it, like this:

def run_cmd(cmd):
  subp = subprocess.Popen(cmd,
  shell=False,
  stdout=subprocess.PIPE,
  stderr=subprocess.STDOUT)
  stdout, stderr = subp.communicate()
  return stdout.decode("utf-8")

 

try:
  stdout = json.loads(stdout)
  status = stdout["retcode"]
  except json.decoder.JSONDecodeError:
  raise ValueError(f"[submit_job]fail, stdout:{stdout}")
  if status != 0:
  raise ValueError(f"[submit_job]fail, status:{status}, stdout:{stdout}")
  return stdout

Guess you like

Origin www.cnblogs.com/SunshineKimi/p/12658471.html