Home > Blockchain >  How can I get the response of an AppleScript dialog box in python?
How can I get the response of an AppleScript dialog box in python?

Time:08-15

I'm trying to use python to create a dialog box prompt with buttons using AppleScript for my Mac.

With the regular dialog box with 'OK' and 'Cancel' I have been simply doing r = os.system("osascript -e 'Tell application \"System Events\" to display dialog \"" body "\"'") because r == 0 if 'OK' is pressed, and r == 256 if 'Cancel' is pressed.

But now I want buttons. I tried r = os.system("osascript -e 'Tell application \"System Events\" to display dialog \"Would you like do download audio or video?\" buttons {\"Audio\", \"Video\"}'") but both buttons return r == 0 if clicked.

I've tried using subprocess.Popen() based on some examples online, but I'm getting errors because I don't really understand it. I can't find an example online that uses AppleScript like I'm using.

Can anyone please point me in the right dirrection for how to do this?

CodePudding user response:

Shell commands send their results to standard output or standard error. AppleScript’s display dialog returns a record ( {button returned: "OK"} for example), with the shell returning the textual representation. You can wrangle the returned text to get the button title, or just have AppleScript return the desired record key, for example:

import os
r = os.system("osascript -e 'tell application \"System Events\" to return button returned of (display dialog \"Would you like do download audio or video?\" buttons {\"Audio\", \"Video\"})'")

Note that using os.system is not recommended these days.

CodePudding user response:

Empirical answer follows...

Try running your osascript command directly in the Terminal, rather than via Python and its subprocess module. Then you can examine both the exit status, and the output on stdout and stderr so you know where to look in Python.


So, first let's look at exit status, just using the Terminal:

osascript -e "SOMETHING"
echo $?

The value printed will match the exit staus from Python subprocess, so try clicking different buttons and see what you get.


Next, look at stdout and stderr. So, run your osascript command again but redirect the stdout to a file called stdout.txt and the stderr to a file called stderr.txt:

osascript -e "SOMETHING" > stdout.txt 2> stderr.txt

Run a few times selecting different options and pressing different buttons in your dialog, but check the contents of stdout.txt and stderr.txt after each using:

cat stdout.txt
cat stderr.txt

When you know whether the output you want is in the exit status, or on stdout or stderr you will know what to look for in Python.

  • Related