1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#! /usr/bin/python
import os, re, string, sys, getopt, signal
def version():
print "Generic Colouriser 1.1"
sys.exit()
def help():
print "Generic Colouriser 1.1"
print
print "grc [options] command [args]"
print
print "Options:"
print "-e --stderr redirect stderr. If this option is selected, "
print " do not automatically redirect stdout"
print "-s --stdout redirect stdout, even if -e is selected"
print "-c name --config=name use name as configuration file for grcat"
print "--colour=word word is one of: on, off, auto"
print
sys.exit()
def keybint(signum, frame):
try:
os.kill(pid1, signal.SIGINT)
except: # if the subprocess already died
pass
try:
optlist, args = getopt.getopt(sys.argv[1:], "sec:", ["stdout", "stderr", "config=", "colour="] )
except:
help()
if not args:
help()
stdoutf = 0
stderrf = 0
# configure file for grcat
cfile = ""
colour = 1
for i in optlist:
if i[0] in ["--stderr", "-e"]:
stderrf = 1
elif i[0] in ["--stdout", "-s"]:
stdoutf = 1
elif i[0] in ["--config", "-c"]:
cfile = i[1]
elif i[0] == "--colour":
if i[1] == "on":
colour = 1
elif i[1] == "off":
colour = 0
elif i[1] == "auto":
colour = sys.stdout.isatty()
else:
help()
stdoutff = 1
stderrff = 0
if stderrf == 1:
stdoutff = 0
stderrff = 1
if stdoutf == 1:
stdoutff = 1
conffile = None
if cfile == "":
home = []
if os.environ.has_key('HOME'):
home = [os.environ['HOME']+"/.grc/grc.conf"]
conffilenames = home + ["/etc/grc.conf"]
for i in conffilenames:
if os.path.isfile(i):
conffile = i
break
regexplist = []
if conffile:
f = open(conffile, "r")
while 1:
l = f.readline()
if l == "":
break
if l[0] == "#" or l[0] == '\012':
continue
regexp = l[:-1]
if re.search(regexp, string.join(args)):
cfile = f.readline()[:-1]
break
signal.signal(signal.SIGINT, keybint)
if cfile != "" and colour:
cho, chi = os.pipe()
pid1 = os.fork()
if pid1 == 0: # child
if stdoutff:
os.dup2(chi, 1)
if stderrff:
os.dup2(chi, 2)
os.close(cho)
os.close(chi)
os.execvp(args[0], args)
pid2 = os.fork()
if pid2 == 0: # child
os.dup2(cho, 0)
os.close(chi)
os.close(cho)
os.execvp("grcat", ["grcat", cfile])
try:
status = os.waitpid(pid1, 0)[1]
except OSError: # interrupted system call
status = None
pass # this is probably not correct
os.close(chi)
os.waitpid(pid2, 0)
os.close(cho)
sys.exit(status and os.WEXITSTATUS(status))
else:
if os.fork() == 0:
os.execvp(args[0], args)
try:
status = os.wait()[1]
except OSError: # interrupted system call
status = None
pass # this is probably not correct
sys.exit(status and os.WEXITSTATUS(status))
|