strange subprocess behavior when calling ps

Jean-Michel Pichavant jeanmichel at sequans.com
Wed Nov 17 05:34:42 EST 2010


Roger Davis wrote:
> Hi all,
>   
[snip]

> Roger Davis
>
> ##### code follows
>
> #!/usr/bin/python
> import sys
> import subprocess
>
> def main():
>
> 	psargs= ["/bin/ps", "-e"]
> 	try:
> 		ps= subprocess.Popen(psargs, stdout=subprocess.PIPE, close_fds=True)
> 		psout= ps.communicate()[0]
> 		pslines= psout.splitlines()
> 		for line in pslines:
> 			print "%s" % line
> 	except KeyboardInterrupt:
> 		print "Keyboard interrupt received -- terminating."
> 		sys.stdout.flush()
> 		sys.exit(-1)
> 	except:
> 		print "%s: unexpected error in generation of system process list" %
> prognm
> 		sys.stdout.flush()
> 		sys.exit(-1)
>
> main()
>   


Completely off topic but I think the try clause could be rewritten that way:

try:
	ps= subprocess.Popen(psargs, stdout=subprocess.PIPE, close_fds=True)
	psout= ps.communicate()[0]
	pslines= psout.splitlines()
	for line in pslines:
		print "%s" % line
except KeyboardInterrupt:
	print "Keyboard interrupt received -- terminating."
finally:
	sys.stdout.flush()


Don't use bare except clause, you're masking syntax errors for instance, 
which will be flagged as 'unexpected error in generation ...".
In a more general manner, if something unexpected happens it's better to 
just let the exception raise uncought. If you want to handle some 
errors, meaning you're kindof expecting them then add a explicit clause 
(like you did with KeyboardInterrupt).

JM


PS : "except Exception :" will catch most of the exceptions (all 
inheriting from that class). It's better than using a bare "except :" 
clause. (Exception won't catch SyntaxError)



More information about the Python-list mailing list