-1

I usually use very simply subprocess.check_output:

process = subprocess.check_output("ps aux", shell=True)
print process #display the list of process

If I fear there is something in stderr, I use it like that:

process = subprocess.check_output("ps aux 2> /dev/null", shell=True)
print process #display the list of process

But I have a problem with nginx -V:

modules = subprocess.check_output("nginx -V", shell=True) #display the result
print modules #empty

modules = subprocess.check_output("nginx -V 2> /dev/null", shell=True) #display nothing
print modules #empty

Why is the command nginx -V behaving differently (all printing in stderr)? How can I design esealy a workaround with ``subprocess.check_output`?

Shan-x
  • 1,146
  • 6
  • 19
  • 44
  • It might be that a process is specifically printing to the terminal it is run on instead of the normal channels. – languitar Feb 17 '17 at 09:55

1 Answers1

0

The way to redirect standard error to standard output in the shell is 2>&1 but you would do well to avoid using the shell at all here.

p = subprocess.Popen(['nginx', '-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if out == '':
    modules = err
modules = out

If you have a more recent Python, also consider switching to subprocess.run()

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • See also http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess/36008455#36008455 for a general discussion of why to avoid `shell=True`. – tripleee Feb 17 '17 at 10:01