Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between subprocess Popen/call/check_output

Hi everyone can anyone elaborate on the difference between

subprocess.Popen
subprocess.call
subprocess.check_output

and also if possible then please explain difference between x.readlines() versus x.communicate()?

i.e difference between

import subprocess
from subprocess import PIPE
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
**out = ls.stdout.readlines()**
print out

and

import subprocess
from subprocess import PIPE
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.communicate()
print out
like image 331
Owais Ahmad Avatar asked Sep 02 '25 08:09

Owais Ahmad


1 Answers

call and check_output (along with check_call) are just utility functions which call Popen under the hood.

  • call returns the exit code of child process
  • check_call raises CalledProcessError error if exit code was non zero
  • check_output same as above but also returns output.

The difference between readlines and communicate is that readlines is simply a function made on the buffer (stdout) while communicate is a method of process class so it can handle different exceptions, you can pass input in it, and it waits for the process to finish.

Read more here

like image 189
Dunno Avatar answered Sep 04 '25 22:09

Dunno