在Python中查找当前终端选项卡的当前目录

时间:2014-12-12 18:28:29

标签: python macos bash applescript

有没有办法用Python,子处理Bash和/或AppleScript,让我获得OSX中最前面的Terminal.app选项卡和窗口的当前工作目录?

我已经在AppleScript: how to get the current directory of the topmost Terminal中尝试了解决方案。它在我的脚本中不起作用。

我使用Python通过以下函数运行AppleScript:

def run(script):
    "Returns the result of running string in osascript (Applescript)"

    if hasattr(script, "encode"): #Assumes Python 3
        script = script.encode("utf-8")

    osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
    results, err = osa.communicate(script)

    if err:
        raise Exception(err)

    return results.decode("utf-8")

我尝试通过以下电话使用建议的答案:

def getTerminalDir():
    script = '''
        tell application "Terminal"
            do shell script "lsof -a -p `lsof -a -c bash -u $USER -d 0 -n | tail -n +2 | awk '{if($NF==\"" & (tty of front tab of front window) & "\"){print $2}}'` -d cwd -n | tail -n +2 | awk '{print $NF}'"
        end tell
    '''
    result = run(script)
    return result

当我这样做时,我收到以下错误:

Exception: 126:127: syntax error: Expected end of line but found “"”. (-2741)

2 个答案:

答案 0 :(得分:1)

知道了。感谢有用的AppleScript见解,这有助于实现此解决方案,Zero

from subprocess import Popen, PIPE, check_output, STDOUT

def runAppleScript(script):
    "Returns the result of running string in osascript (Applescript)"

    if hasattr(script, "encode"): #Assumes Python 3
        script = script.encode("utf-8")

    osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
    results, err = osa.communicate(script)
    if err:
        raise Exception(err)

    return results.decode("utf-8")

def runBash(command):
    output = check_output(command, stderr=STDOUT, shell=True)
    return output

def getCurrentTerminalTTYS():
    script = '''
    tell application "Terminal"
        return (tty of selected tab of front window)
    end tell
    '''
    result = runAppleScript(script)
    return result.strip()

def getPathForTTYS(ttys):
    lsof = runBash('lsof').split('\n')
    process = None
    for line in lsof:
        if ttys in line:
            process = line.split()[1]
            break
    path = None
    for line in lsof:
        if 'cwd' in line and process in line:
            path = ' '.join(line.split()[8:])
            break
    return path

def getCurrentTerminalPath():
    ttys = getCurrentTerminalTTYS()
    return getPathForTTYS(ttys)

可以使用

将其存储为字符串
path = getCurrentTerminalPath()

答案 1 :(得分:1)

您可以尝试以下内容:

tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    do script "pwd" in selected tab of window 1
    set tabContents to contents of selected tab of window 1
end tell

set myPath to paragraph -2 of (do shell script "grep . <<< " & quoted form of tabContents)