How do I bring a processes window to the foregroun

2019-02-26 04:08发布

I have a simple shell/python script that opens up other windows. I'd like to bring the terminal where the script is running to the foreground when the script has finished.

I know the process ID of my parent window. How can I bring a given window to the foreground? I imagine I have to find out the window name from the PID along the way.

2条回答
甜甜的少女心
2楼-- · 2019-02-26 04:15

Not sure if there's a proper way, but this works for me:

osascript<<EOF
tell application "System Events"
    set processList to every process whose unix id is 350
    repeat with proc in processList
        set the frontmost of proc to true
    end repeat
end tell
EOF

You can do it with osacript -e '...' too.

Obviously change the 350 to the pid you want.

查看更多
混吃等死
3楼-- · 2019-02-26 04:34

Thanks to Mark for his awesome answer! Expanding on that a little:

# Look up the parent of the given PID.
# From http://stackoverflow.com/questions/3586888/how-do-i-find-the-top-level-parent-pid-of-a-given-process-using-bash
function get-top-parent-pid () {
    PID=${1:-$$}
    PARENT=$(ps -p $PID -o ppid=)

    # /sbin/init always has a PID of 1, so if you reach that, the current PID is
    # the top-level parent. Otherwise, keep looking.
    if [[ ${PARENT} -eq 1 ]] ; then
        echo ${PID}
    else
        get-top-parent-pid ${PARENT}
    fi
}

function bring-window-to-top () {
    osascript<<EOF
    tell application "System Events"
        set processList to every process whose unix id is ${1}
        repeat with proc in processList
            set the frontmost of proc to true
        end repeat
    end tell
EOF
}

You can then run:

bring-window-to-top $(get-top-parent-pid)

Quick test using:

sleep 5; bring-window-to-top $(get-top-parent-pid)

And swap to something else. After 5 seconds the terminal running your script will be sent to the top.

查看更多
登录 后发表回答