I want to call a process and output both its stdd and stout to a string for inspection. This code triggers the Unexpected error block.
try:
proc = subprocess.Popen('ls -ddd 1>&2', stdout=subprocess.PIPE, stderr=subprocess.PIPE,)
stdout,stderr = proc.communicate()
if len(stderr)>1:
actualResult =stderr
else:
actualResult =stdout
print actualResult
except:
print "Unexpected error"
Ive based it on http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html but am obviously missing something. Is it possible to do this inside a try block?
You should never use a generic
Exceptclause, as this will catch any exception and prevent you from fixing the script (Each and any exception is caught, so how do you know which one occured?).Here, if you remove the Except block, you’re faced with a
OSError: [Errno 2] No such file or directory. This means thatsubprocess.Popenhasn’t found the executable you asked for on your path.Which is happening because you didn’t pass
shell = trueto yourPopencall.Not passing
shell = Truewhich means thatsubprocess.Popenis looking for an executable called"ls -ddd 1>&2", which is equivalent to literally writing"ls -ddd 1>&2"at your prompt and would result in a “command not found!”(unless you happened to have an executable file with spaces and ampersands in the filename!)
This is of course not what you want, what you want is to call the
lscommand with the argument-dddand redirecting1>&2.Long story short, add
shell = Trueto your call.