#!/usr/bin/env python3 # -*- coding: utf-8 -*- from os import environ,getpid from subprocess import PIPE,Popen from sys import argv _termstrs = ('ermina','onsole') _psmap = {} _psrec = {} _wmout = [] _lt = (list,tuple) _sbb = (str,bytes,bytearray) _tv = (TypeError,ValueError) def cmdout(cmd): """Run a command line returning its output as a list of lines (strs).""" if not isinstance(cmd,_lt): raise TypeError('argument 1 (command) must be a list or tuple (of strings).') if not all(isinstance(x,_sbb)for x in cmd): raise TypeError('argument 1 (command) must be (a list or tuple of) strings.') with Popen(cmd,stdout=PIPE,universal_newlines=all(isinstance(x,str)for x in cmd)) as p: return p.stdout.read().splitlines() def getwsdata(): """Get window manager data as a list of output lines (list of strs).""" _wmout[:] = [] for line in cmdout(['wmctrl','-lp']): wm = line.split() try: wm[1] = int(wm[1]) wm[2] = int(wm[2]) except ValueError: continue _wmout.append(wm) return _wmout def getpsdata(): """Get process data as a map by PID of lists of strs.""" _psrec.clear() _psmap.clear() for line in cmdout(['ps','-ef']): ps = line.split() try: ps[1] = int(ps[1]) ps[2] = int(ps[2]) except ValueError: continue _psmap[ps[1]] = ps _psrec[ps[1]] = line return def getpidtermpid(p): """Get PID of terminal that given process is running under.""" try: p = int(p) except _tv: return None getpsdata() while p>1: ps = _psmap[p] p = ps[2] for x in range(3,len(ps)): for y in _termstrs: if y in ps[x]: return ps[1] return -1 def getpidws(p): """Get workspace number given PID is in -or- -1.""" try: p = int(p) except _tv: return None getwsdata() for x in _wmout: if p==x[2]: return x[1] return None def _main(args): p = getpid() if args[1:]: try: p = int(arg[1]) except tv: pass t = getpidtermpid(p) if t is None: return 1 w = getpidws(t) if w is not None: print(w) return 1 if __name__ == '__main__': try: result = _main(argv) except BrokenPipeError: result = 141 except KeyboardInterrupt: print(flush=True) result = 98 if result is None or result is True: result = 0 elif result is False: result = 1 exit(result)