Reputation: 4328
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?
Upvotes: 0
Views: 131
Reputation: 55303
You should never use a generic Except
clause, 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 that subprocess.Popen
hasn't found the executable you asked for on your path.
Which is happening because you didn't pass shell = true
to your Popen
call.
Not passing shell = True
which means that subprocess.Popen
is 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 ls
command with the argument -ddd
and redirecting 1>&2
.
Long story short, add shell = True
to your call.
Upvotes: 3