【问题标题】:Python 2 and AppleScript. Dialogue prompts and default answersPython 2 和 AppleScript。对话提示和默认答案
【发布时间】:2018-01-22 08:57:23
【问题描述】:

这只是我用来读取 Mac System Profiler 文件的 XML 数据的 Python 代码的一个小 sn-p,目的是无需手动复制/粘贴详细信息即可将数据添加到数据库。

具体来说,这段代码的 sn-p 提示用户输入“文章编号”以将给定的“.spx”(系统分析器报告)保存在下面。

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" 将指示 spx 文件的名称。

我想将 AppleScript 提示中的“默认答案”的值设置为主 Python 脚本中另一个变量的值(在本例中为“exampleString”)。 “12345”在这里只是占位符文本。

最终目标是尽量减少最终用户的数据输入。

感谢您的帮助。

【问题讨论】:

    标签: python-2.7 applescript


    【解决方案1】:

    只要字符串格式就好了!

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

    并应用于你的程序:

    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)])
    

    【讨论】:

    • 太棒了!用“日期作为字符串”测试进行了尝试,它仍然有效。感谢磨坊。
    • 从不执行包含未经处理的输入的生成代码。如果 exampleString 包含双引号或反斜杠字符怎么办?除了冒意外行为/错误的风险外,这还允许代码注入攻击。对任何语言都完全不负责任。 Here is an example of how to parameterize an osascript correctly.
    • Python 的内置格式足够聪明,可以阻止这种情况。如果您将此标签下的对象保存在数据库中,那么这是一个不同的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    相关资源
    最近更新 更多