0

Here is just a small snippet of the Python code I use to read the XML data of Mac System Profiler files for the purpose of adding the data to a database without having to copy/paste the details manually.

Specifically this snippet of code prompts the user to enter an "Article Number" to save the given ".spx" (System Profiler Report) under.

import subprocess

exampleString = "12345"

theText = subprocess.check_output(['osascript', '-e',
                              r'''set theText to text returned of (display dialog "Enter new Article Number here:
                               \n\nElse just press OK" default answer "" with title "Hardware Paster v1.0" with icon 2)'''
                              ])

"theText" will go to on dictate the name of the spx file.

I would like to set the value of the "default answer" inside of the AppleScript prompt with the value of another variable inside the main python script ("exampleString" in this case). The "12345" is just placeholder text here.

The ultimate aim is to minimise data-entry by the end user.

Thanks for your help.

William Lombard
  • 337
  • 1
  • 3
  • 14

1 Answers1

1

Just string format and you're good!

>>> exampleString = "world"
>>> 'hello there "{}"!'.format(exampleString)
'hello there "world"!'

And applied to your program:

exampleString = "12345"

template = r'''set theText to text returned of (display dialog "Enter new Article Number here:
\n\nElse just press OK" default answer "{}" with title "Hardware Paster v1.0" with icon 2)'''

theText = subprocess.check_output(
    ['osascript', '-e', template.format(exampleString)])
ddg
  • 1,090
  • 1
  • 6
  • 17
  • That is super! Tried it out with a "date as string" test and it still works. Thanks a mill. – William Lombard Jan 22 '18 at 09:13
  • *Never* execute generated code containing unsanitized inputs. What if the exampleString contains a double quote or a backslash character? Aside from risking unintended behaviors/errors, this is what allows code injection attacks. Totally irresponsible in any language. [Here is an example of how to parameterize an osascript correctly.](https://stackoverflow.com/a/23923167/7926970) – foo Jan 22 '18 at 19:10
  • Python's builtin format is smart enough to stop that. If you are saving the objects under this label in a database, then that's a different issue. – ddg Sep 19 '18 at 04:01