Using apple script to find out and compare process path by PID - macos

I am using Apple Script to find the process PID by name, like ...
set appName to "KKK"
tell application "System Events"
set processPID to (unix id of processes whose name is appName)
end tell
With this script, I can know about PIDs of all processes which name is "KKK".
But I have a question here.
For example, there has three "KKK" process, "/FolderA/KKK", "FolderB/KKK", "FolderC/KKK"
I want to kill the process of "/FolderA/KKK", so I need to know which PID is belong to "/FolderA/KKK".
After run my script, I can get three PIDs, what can I actually do in Apple Script to distinguish which PID is what I want? (Maybe to get the process path by PID?)
Thank you

Instead of the name check for the path of the application, this is an example checking for Messages.app.
set appPath to "/Applications/Messages.app"
tell application "System Events"
set processPID to (unix id of 1st process whose POSIX path of application file is appPath)
end tell

It also can be done using the following:
do shell script "kill -9 $(ps -x | awk '/[F]olderA\\/KKK/{print $1}')"
You can also add ; exit 0 to the end to eat an error if the app isn't running and have no need to check or trap otherwise:
do shell script "kill -9 $(ps -x | awk '/[F]olderA\\/KKK/{print $1}'); exit 0"

Related

how to close an active document in Mac OS using shell script

I am closing active document using apple script as below
tell application "Microsoft Word"
activate
try
if not (exists active document) then error number -128
close active document saving yes
on error
end try
end tell
want to do similar action using shell script. I want to gracefully close it and don't want to use kill command . And I don't want to use osascript to call an apple script . I want a graceful way using native shell commands
Hi you can use osascript in the shell code
#!/bin/sh
osascript <<EOF
tell application "$1"
close (every window whose name is "$2")
end tell
EOF
Compile this code and make filename.sh
or you can use
#!/bin/sh
osascript <<EOF
tell application "Preview"
close (every window whose name is "$1")
end tell
EOF
To use this from cmd type $./file_name Preview application name
Here I used the reference of https://ss64.com/osx/osascript.html

Get PIDs of all open windows on MacOS

I tried to use the following AppleScript to get the PIDs of all the windows (including ones that are minimized). This script doesn't get the PIDs of windows on other desktops.
Is there any workaround for this so I can still get a list of opened windows across all desktops without having to activate individual processes and checking if they have windows?
tell application "System Events"
repeat with proc in (every process)
if exists(first window of proc) then
set pid to unix id of proc
log pid
end if
end repeat
end tell
PS, I'm not too proficient with AppleScript. I've managed to hack this together using StackOverflow. This might not be the most efficient way to do what I'm trying to do.
Looks like I got this to work with this ugly bash-applescript hack
osascript -e "tell application \"System Events\"
repeat with proc in (processes where background only is false)
set pname to name of proc
log pname
end repeat
end tell" 2>&1 |
while read line
do
echo "process " $line
pgrep $line
done
This prints something like
process Finder
818
process Google Chrome
3730
3734
3740
5838
process iTerm2
3750
4210
process Sublime Text
3822
Where PID 818 belongs to the Finder process and so on.

How do I bring a processes window to the foreground on OS X?

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.
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.
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.

Access built-in Power Manager? states

Im trying to write a super simple applescript that will launch the OneDrive App, or ensure it is open, whenever the machine's power source is set to plugged in, and will quit, or make sure is closed, when the power source is set to battery.
I'm having trouble finding how to access the built-in "power indicator" in Yosemite. All of my searches lead to old, irrelevant results from years ago.
Edit: I think I will have to use a do shell script within the applescript using pmset -g batt
Now drawing from 'AC Power'
-InternalBattery-0 100%; charged; 0:00 remaining
And parse this result, but I am not sure how.
Edit: Here it is for anyone in the future who may want something similar:
global appName
on appIsRunning()
tell application "System Events" to (name of processes) contains appName
end appIsRunning
on acIsConnected()
return (do shell script "system_profiler SPPowerDataType | grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
end acIsConnected
on toggleApp()
if my acIsConnected() then
if not my appIsRunning() then
tell application "Finder"
open application file (appName & ".app") of folder "Applications" of startup disk
end tell
end if
else
tell application appName
quit
end tell
end if
end toggleApp
-- This will only be executed once.
on run
set appName to "OneDrive"
end run
-- This will be executed periodically, specified in seconds, every return.
on idle
my toggleApp()
-- Execute every 2 minutes.
return 120
end idle
-- Not mandatory, but useful for cleaning up before quiting.
on quit
-- End handler with the following line.
continue quit
end quit
Here is a one-liner that polls for connected status, since I guess you can have less than 100% and still be connected (charging).
set acConnected to (do shell script "system_profiler SPPowerDataType |grep -q 'Connected: Yes' && echo \"true\" || echo \"false\"") as boolean
Here's another one liner...
set acConnected to last word of paragraph 1 of (do shell script "ioreg -w0 -l | grep ExternalChargeCapable")
If you are happy to use a third party tool, you can avoid polling for the battery state. This will make your script more efficient.
Power Manager can run AppleScripts when the battery state changes. How to Run a Command When Switching to Battery Power, walks through how to set this up for scripts.
Swap out the #!/bin/sh for #!/usr/bin/osascript in the script, and you can use AppleScript.
Disclaimer: I wrote Power Manager and can answer comments about how it works.
Provided you have battery icon on screen's top right:
tell application "System Events" to tell process "SystemUIServer" ¬
to value of attribute "AXDescription" of ¬
(first menu bar item whose value of attribute "AXDescription" ¬
begins with "Battery") of menu bar 1
You get "Battery: Charged" or "Battery: Calculating Time Remaining… " or something else

Can't make Unix ID of Process into text?

I have a modbook with a glitchy digitizer board. Until I can re-shield the cable that is causing the glitch I just want to turn the digitizer off. I found a page which taught me some code and I used it successfully last night. Upon reboot, however, it doesn't work anymore:
The script:
tell application "System Events"
set PTD to (unix id of process "PenTabletDriver") as text
do shell script "kill -STOP " & quoted form of (PTD)
end tell
The error message:
error "Can’t make «class idux» of «class prcs» \"PenTabletDriver\" of
application \"System Events\" into type text." number -1700 from
«class idux» of «class prcs» "PenTabletDriver" to text
Can I alter the code somehow to fix this problem?
PS:
I have read this post and, though it's similar, I do not understand how it could be applied to my problem.
Life is too short to mess with AppleScript. Try running the following command at the terminal prompt:
pkill -STOP PenTabletDriver
Also, check your login items to see if the driver is automatically started each time you log in. (More likely, though, is that it's configured to start at boot time via launchd.)
You can save the following script in a little applet:
set shellStr to "pkill -STOP PenTabletDriver"
do shell script shellStr
and run it whenever you need.
I think the other answers make a good point, a shell command is nice and quick. BUT, if you must have it in AppleScript, this seems to work for me....
tell application "System Events"
set PTD to (unix id of process "iTunes")
do shell script "kill -STOP " & quoted form of (PTD as text)
end tell
which results to
tell application "System Events"
get unix id of process "iTunes"
--> 37987
do shell script "kill -STOP '37987'"
--> error number -10004
end tell
tell current application
do shell script "kill -STOP '37987'"
--> ""
end tell
The Process ID is just a number so there is no need to quote it...
tell application "System Events"
set PTD to (unix id of process "iTunes")
do shell script "kill -STOP " & PTD
end tell
The above code is sufficient.

Resources