Skip to content

Instantly share code, notes, and snippets.

@13k
Created May 21, 2010 10:45
Show Gist options
  • Select an option

  • Save 13k/408700 to your computer and use it in GitHub Desktop.

Select an option

Save 13k/408700 to your computer and use it in GitHub Desktop.
#!/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
print
print "Python sed shell"
print
print "Any input is equivalent to the command:"
print
print " echo '<data>' | sed -re '<regex>'"
print "where <regex> is the input as a Python expression"
print
print "To set <data>, use the function d(), like:"
print ' >> d("hello")'
print
print "To see <data>'s content, use the function d() without argument"
print
print "<data> defaults to %s" % _data
print
print
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