How to display progress of a Python script?

You could use subprocess.run() to call osascript, passing in the AppleScript text to call a KM "Display Progress" dialog. Demo -- save the below into a .py file and run it with python3:

import time
import subprocess

preXML = """
			tell application \"Keyboard Maestro Engine\" to do script \"<dict>
				<key>ActionUID</key>
				<integer>100012857</integer>
				<key>MacroActionType</key>
				<string>DisplayProgress</string>
				<key>Progress</key>
				<string>
"""
postXML = """
</string>
				<key>Title</key>
				<string>Python Script Progress</string>
			</dict>
\"
return
"""

for i in range(0,10):
	subprocess.run(['osascript', '-e', preXML + str((i + 1) * 10) + postXML])
	time.sleep(1)

You'll have to replace the (i + 1) * 10 bit with your "progress value" -- a number from 0 to 100. And remember to end by setting the progress to 100, either in your Python script or with a KM action, so the dialog is closed.

If you don't have an actual, calculable, progress and just want to show "Hey, we're still busy over here!" -- call the progress dialog with a value of -1 to start, again finishing with 100:

import time
import subprocess

preXML = """
			tell application \"Keyboard Maestro Engine\" to do script \"<dict>
				<key>ActionUID</key>
				<integer>100012857</integer>
				<key>MacroActionType</key>
				<string>DisplayProgress</string>
				<key>Progress</key>
				<string>
"""
postXML = """
</string>
				<key>Title</key>
				<string>Python Script Progress</string>
			</dict>
\"
return
"""

subprocess.run(['osascript', '-e', preXML + "-1" + postXML])

for i in range(0,10):
	print(i)
	time.sleep(1)

subprocess.run(['osascript', '-e', preXML + "100" + postXML])

Not a Pythonista, so no laughing at the back :wink:

There's also an applescript module (https://pypi.org/project/applescript/) -- which I know even less about. My goto would be @drdrang ,and if you tag him three times he may appear... While you are waiting, take a look at the relevant articles on his blog with a site search for "from AppleScript import".

3 Likes