+class Process(object):
+ def __init__(self, pid):
+ self.pid = pid
+
+ @property
+ def stdin(self):
+ return os.readlink("/proc/%s/fd/0" % self.pid)
+
+ @property
+ def stdout(self):
+ return os.readlink("/proc/%s/fd/1" % self.pid)
+
+ @property
+ def cmdline(self):
+ return file("/proc/%s/cmdline" % self.pid).read().split("\x00")
+
+def validProcesses():
+ for pid in filter(str.isdigit, os.listdir("/proc/")):
+ if os.path.exists("/proc/%s/fd/0" % pid):
+ yield Process(pid)
+
+def isatty(filename):
+ try:
+ stdout = file(cur.stdout)
+ return os.isatty(stdout.fileno())
+ except IOError:
+ return False
+
+# Follow from current pid until the end of the chain
+count = 0
+cur = Process(os.getpid())
+while count < 32 and cur.stdout.startswith("pipe:"):
+ last = cur
+ for cur in validProcesses():
+ try:
+ if last.stdout == cur.stdin:
+ count = 0
+ break
+ except OSError:
+ continue
+ else:
+ cur = last
+ count += 1
+ time.sleep(0.001)
+
+# Use colour or not