Created
May 21, 2010 10:45
-
-
Save 13k/408700 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # If Win32, MSYS/cygwin with sed is required | |
| import sys | |
| if __name__ != '__main__': | |
| print "This script must be run, not imported" | |
| sys.exit(1) | |
| try: | |
| import readline | |
| except ImportError: | |
| # readline not available :( | |
| pass | |
| from subprocess import Popen, PIPE | |
| _data = "abcdefghijklmnopqrstuvwxyz" | |
| print "Python sed shell" | |
| print "Any input is equivalent to the command:" | |
| print " echo '<data>' | sed -re '<regex>'" | |
| print "where <regex> is the input as a Python expression" | |
| print "To set <data>, use the function d(), like:" | |
| print ' >> d("hello")' | |
| print "To see <data>'s content, use the function d() without argument" | |
| print "<data> defaults to %s" % _data | |
| class DataSet(Exception): | |
| pass | |
| def d(data=None): | |
| global _data | |
| if data is None: | |
| print _data | |
| else: | |
| _data = data | |
| raise DataSet() | |
| def exit(): | |
| sys.exit(0) | |
| while True: | |
| try: | |
| regexp = input('>> ') | |
| if not isinstance(regexp, basestring): | |
| print '?' | |
| continue | |
| sed = Popen(['sed', '-re', regexp], stdout=PIPE, stdin=PIPE, stderr=PIPE) | |
| stdout, stderr = sed.communicate(_data) | |
| if sed.returncode == 0: | |
| print stdout | |
| else: | |
| print "! %s" % stderr | |
| except DataSet: | |
| continue | |
| except EOFError: | |
| break | |
| except KeyboardInterrupt: | |
| break | |
| except Exception, e: | |
| print "!! %s" % e.msg |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment