]> code.delx.au - monosys/blob - scripts/linux_colorwrap
3273f4740c6f077794d830f018b08202779c088c
[monosys] / scripts / linux_colorwrap
1 #!/usr/bin/env python
2
3 PAGERS = ["less", "more", "most", "tail", "head"]
4
5 # Usage:
6 # * Put this file into ~/bin/colorwrap
7 # * Add these aliases to your bash config
8 # alias ls="colorwrap ls"
9 # alias grep="colorwrap grep"
10
11
12 import os, os.path, sys, time
13
14 class Process(object):
15 def __init__(self, pid):
16 self.pid = pid
17
18 @property
19 def stdin(self):
20 return os.readlink("/proc/%s/fd/0" % self.pid)
21
22 @property
23 def stdout(self):
24 return os.readlink("/proc/%s/fd/1" % self.pid)
25
26 @property
27 def cmdline(self):
28 return file("/proc/%s/cmdline" % self.pid).read().split("\x00")
29
30 def validProcesses():
31 for pid in filter(str.isdigit, os.listdir("/proc/")):
32 if os.path.exists("/proc/%s/fd/0" % pid):
33 yield Process(pid)
34
35 def isatty(filename):
36 try:
37 stdout = file(cur.stdout)
38 return os.isatty(stdout.fileno())
39 except IOError:
40 return False
41
42 # Follow from current pid until the end of the chain
43 count = 0
44 cur = Process(os.getpid())
45 while count < 32 and cur.stdout.startswith("pipe:"):
46 last = cur
47 for cur in validProcesses():
48 try:
49 if last.stdout == cur.stdin:
50 count = 0
51 break
52 except OSError:
53 continue
54 else:
55 cur = last
56 count += 1
57 time.sleep(0.001)
58
59 # Use colour or not
60 command = sys.argv[1]
61 args = sys.argv[1:]
62 if cur.cmdline in PAGERS or isatty(cur.stdout):
63 args.insert(1, "--color=always")
64
65 os.execvp(command, args)
66