Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess.stdout behaves differently with shell=True and shell=False

I have a python script called class.py with one line:

class.py:

print "Hello World"

I run it in a subprocess, like this.

run_subprocess.py:

import subprocess

p = subprocess.Popen(["python", "class.py"], stdin=subprocess.PIPE, shell=True,
                     stdout=subprocess.PIPE)
a = p.communicate()

print a

When I run this (on a Mac), I get an empty command string:

$ python run_subprocess.py
('', None)

When I run this with shell=False, I get the contents of stdout:

run_subprocess.py:

import subprocess

p = subprocess.Popen(["python", "class.py"], stdin=subprocess.PIPE, shell=False,
                     stdout=subprocess.PIPE)
a = p.communicate()

print a


$ python run_subprocess.py
('hello world\n', None)

Why? How can I get the contents of stdout when running subprocess with shell=True?

Thanks, Kevin

like image 989
Kevin Burke Avatar asked Feb 04 '12 03:02

Kevin Burke


1 Answers

The first argument to Popen is interpreted in a different way depending on the value of shell. You need to pass the command and its arguments in a different way. Please, read the documentation (I answered a similar question a couple of days ago).

like image 84
Ricardo Cárdenes Avatar answered Sep 26 '22 06:09

Ricardo Cárdenes