Run OS Command w/ Expected Output


/ Published in: Python
Save to your folder(s)

Run the specified command. If expect is not None then look for the given text in the output. If it is not there we throw an error. expect can also be a list of strings. In that case any match results in success unless matchall=True.


Copy this code and paste it in your HTML
  1. from popen2 import popen4
  2. from types import ListType
  3.  
  4. class RUNError:
  5.  
  6. def __init__( self, cmd, expect, result, nomatch=None ):
  7. self.cmd = cmd
  8. self.expect = expect
  9. self.result = result
  10. self.nomatch = nomatch
  11. if self.nomatch is None:
  12. self.nomatch = []
  13.  
  14. def __repr__( self ):
  15.  
  16. expect = self.expect
  17. if len( self.nomatch ):
  18. expect = self.nomatch
  19.  
  20. return """Ran '%s'; expected '%s', got '%s'""" % ( self.cmd,
  21. str( expect ), self.result )
  22.  
  23. def run( command, expect=None, matchall=False ):
  24. """Run the specified command. If expect is not None then
  25. look for the given text in the output. If it is not there
  26. we throw an error. expect can also be a list of strings. In
  27. that case any match results in success. Unless matchall=True"""
  28.  
  29. stdout,stdin = popen4( command )
  30. result = stdout.read()
  31. result = result.strip()
  32.  
  33. nomatch = []
  34. if not expect is None:
  35. if len( expect ):
  36. if not type( expect ) is ListType:
  37. expect = [ expect ]
  38.  
  39. found = False
  40. for s in expect:
  41. if result.find( s ) > -1:
  42. found = True
  43. if not matchall:
  44. break
  45. else:
  46. nomatch.append( s )
  47.  
  48. if not found:
  49. raise RUNError( command, expect, result, nomatch )
  50. else:
  51. if len( result ):
  52. raise RUNError( command, "<empty string>", result )
  53.  
  54. if matchall and (type( expect ) is ListType) and ( len( nomatch ) ):
  55. raise RUNError( command, expect, result, nomatch )
  56.  
  57. return result

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.