Skip to content

Instantly share code, notes, and snippets.

@ekovac
Created April 4, 2012 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekovac/2305244 to your computer and use it in GitHub Desktop.
Save ekovac/2305244 to your computer and use it in GitHub Desktop.
A utility for determining the current working directory of a shell running inside an xterm or other terminal emulator on X
#!/usr/bin/python
"""
term-pwd
a utility for determining the current working directory of a shell running inside an xterm or other terminal emulator on X
"""
import argparse
import sys
import os
import os.path
import re
from Xlib import X, display, xobject, Xatom
parser = argparse.ArgumentParser(description="Determine the current working directory of a shell running inside an xterm or other terminal emulator on X");
parser.add_argument(dest='xid', metavar='XID', type=str, help="ID of the X Window owned by the terminal emulator.")
parser.add_argument('-r', dest='recurse', action='store_const', const=True, default=False, help="Walk all the way down to the leaf node of the process tree.")
args = parser.parse_args()
args.xid = int(args.xid, 16)
pstree = dict()
pids = [int(x) for x in os.listdir("/proc") if x.isdigit()]
stat_re = re.compile("(\d+) (\S+) (.) (\d+)");
sys.stdout = open("/dev/null", "w")
disp = display.Display()
sys.stdout = sys.__stdout__
nwm_atom = disp.get_atom("_NET_WM_PID", 0)
window = xobject.drawable.Window(disp.display, args.xid)
term_pid = window.get_property(nwm_atom, Xatom.CARDINAL, 0, 32)
term_pid = term_pid.value[0]
def ppid(pid):
path = os.path.join("/proc", str(pid), "stat");
with open(path) as stat:
return int(stat_re.match(stat.readline()).group(4))
for pid in pids:
my_ppid = ppid(pid)
if pstree.has_key(my_ppid):
pstree[my_ppid].add(pid)
else:
pstree[my_ppid] = set()
pstree[my_ppid].add(pid)
shell_pid = pstree[term_pid].pop()
cwd_path = os.readlink(os.path.join("/proc", str(shell_pid), "cwd"))
print cwd_path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment