0

I have below code snippet. Will the last two print statements equivalent? Kindly advise.

P1 = Popen(shlex.split(hdfs_rm_command), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
           universal_newlines=True)
o4, e4 = P1.communicate()
if P1.returncode != 0:
    print(e4)
    print(P1.stderr)
tripleee
  • 175,061
  • 34
  • 275
  • 318

1 Answers1

0

No, the stderr member of a Popen object is a filehandle, not a string which was previously written to that filehandle.

You should probably not be using Popen directly, anyway; this is one of the many situations where all you need is a single run call, which will also then actually provide the interface you are asking about.

P1 = subprocess.run(shlex.split(hdfs_rm_command),
    capture_output=True,
    universal_newlines=True)
if P1.returncode != 0:
    print(P1.stderr)
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • In this case, will I not need to invoke communicate() in order to wait for my command to complete? – Vishal Agarwal May 22 '21 at 17:28
  • No, `run` takes care of all the chaff you need to do yourself when you use the low-level `Popen` directly. – tripleee May 22 '21 at 17:31
  • It works but can you please explain why you prefer to use subprocess instead of popen? Thanks! – Vishal Agarwal May 22 '21 at 19:28
  • Because doing things yourself when the library can do them for you is inefficient, verbose, and error-prone; but don't take it from me, find the same recommendation in the `subprocess` documentation. Maybe review https://stackoverflow.com/questions/4256107/running-bash-commands-in-python/51950538#51950538 which quotes the relevant section and discusses the topic further. – tripleee May 23 '21 at 08:12