iTerm2:如何使用 applescript 获取 shell 命令的输出

iTerm2:如何使用 applescript 获取 shell 命令的输出

我想将通过 iTerm2 的 applescript 运行的 shell 命令的输出放入 applescript 变量中。我尝试了以下方法,但没有成功:

tell application "iTerm"
  activate
  try
    set _session to current session of current terminal
  on error
    say "Error"
  end try
  tell _session
    set Directory to write text "pwd"
    get Directory
    set Directory to exec command "pwd"
    get Directory
  end tell
end tell

感谢您的帮助!

答案1

你可以尝试一下。

tell application "iTerm"
    activate
    try
        set _session to current session of current tab of current window
    on error
        say "Error"
    end try
    tell _session
        write text "pwd"
        set terminalContent to text of _session
    end tell
end tell
set output to paragraph -2 of trim(true, terminalContent)

on trim(theseCharacters, someText)
    if class of someText is text and length of someText > 0 then
        -- default values (all whitespace)
        if theseCharacters is true then ¬
            set theseCharacters to {" ", tab, ASCII character 10, return, ASCII character 0}

        repeat until first character of someText is not in theseCharacters
            set someText to text 2 thru -1 of someText
        end repeat

        repeat until last character of someText is not in theseCharacters
            set someText to text 1 thru -2 of someText
        end repeat
    end if

    return someText
end trim

write text这将返回您在上述代码第 9 行中指定的命令的输出。

相关内容