Here is an example of passing a value to an AppleScript, and retrieving values from user input via a Python3 subprocess invocation:
#!/usr/bin/env python3
import subprocess
import sys
import os
import re
try:
from subprocess import DEVNULL # python3
except ImportError:
DEVNULL = open(os.devnull, 'wb') # python2
#!/usr/bin/python
# coding: utf-8
import os
import sys
import subprocess
ascript = '''
use scripting additions
on run argv
display dialog "current directory location is: " & (item 1 of argv) with title "Passed argument"
try
set query to text returned of (display dialog "Enter your name, rank, and serial number each separated by a single semi-colon (;) : " default answer "")
on error -128
return "Cancel"
end try
if not query = "" then
return query
else
return "Invalid User Input"
end if
end run
'''
def main():
os.chdir(os.path.dirname(__file__))
thisdir = os.getcwd()
try:
proc = subprocess.check_output(['osascript', '-e', ascript, thisdir],
shell=False, stderr=DEVNULL)
if 'Cancel' in proc.decode('utf-8'): # User pressed Cancel button
sys.exit(proc.decode('utf-8'))
elif 'Invalid User Input' in proc.decode('utf-8'):
sys.exit(proc.decode('utf-8'))
except subprocess.CalledProcessError as e:
print('Python error: [%d]\n%s\n'.format(e.returncode, e.output))
# split user input on semi-colon
details = proc.decode('utf-8').split(';')
if not details:
print("empty user input")
elif len(details) == 3:
print("{}\t{}\t{}".format(*details))
else:
print("User did not input all three requests")
if __name__ == '__main__':
sys.exit(main())