Python Forum
what workspace is my terminal in?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what workspace is my terminal in?
#1
this script is intended for a Posix environment. it was developed and tested in Xubuntu 18.04 LTS with Python 3.6.8.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os import getpid
from subprocess import PIPE,Popen

def cmdout(cmd):
    with Popen(cmd,stdout=PIPE,universal_newlines=True) as proc:
        f = proc.stdout
        out = f.read()
        f.close()
    return out

def getmyterminal(p):
    while p>1:
        ps = psmap[p]
        if any('terminal' in ps[x] for x in range(4,len(ps))):
            return ps
        p = ps[2]
    return None

def printancestry(p):
    while p>1:
        print(psrec[p])
        p = psmap[p][2]
    print(psrec[p])
    return

pid = getpid()

psout = cmdout(['ps','-ef'])
psmap = {}
plist = []
psrec = {}
for line in psout.splitlines():
    ps = line.split()
    try:
        ps[1] = int(ps[1])
        ps[2] = int(ps[2])
    except ValueError:
        continue
    psmap[ps[1]] = ps
    plist.append(ps[1])
    psrec[ps[1]] = line

#printancestry(pid)

termps = getmyterminal(pid)
termpid = termps[1]
termppid = termps[2]
assert termppid == 1

wmout = cmdout(['wmctrl','-lp'])
ws = None
for line in wmout.splitlines():
    wm = line.split()
    try:
        wm[1] = int(wm[1])
        wm[2] = int(wm[2])
    except ValueError:
        continue
    if wm[2] == termpid:
        ws = wm[1]

if isinstance(ws,int):
    print(str(ws))
it can also be downloaded from http://ipal.net/python/termws.py if you prefer that method. its sha256 checksum is c2c3c7d838dd7c1200a3482d0edb766a3b9f76c5358c022c6e8bdc6dd68cb537.

yeah, i know, line 10 is unnecessary since context management under with will close the pipe.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
what workspace is my terminal in? - by Skaperen - Nov-13-2019, 08:31 AM
RE: what workspace is my terminal in? - by Skaperen - Nov-13-2019, 11:34 PM
RE: what workspace is my terminal in? - by Skaperen - Nov-14-2019, 04:39 AM
RE: what workspace is my terminal in? - by Skaperen - Nov-14-2019, 09:17 PM
RE: what workspace is my terminal in? - by Skaperen - Nov-15-2019, 02:04 AM
RE: what workspace is my terminal in? - by Skaperen - Nov-16-2019, 03:56 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020