Apple Script:how 将用户输入保存到文本文件

Apple Script:how to save user input to text file

我在 python 应用程序中使用 apple 脚本,如何将用户提供的输入保存为文本文件?

 firstname = """
    display dialog "Enter your first name " default answer "" ¬
    buttons {"Submit"}
    """

考虑以下任一解决方案:

解决方案 A:使用 Python 将用户输入保存到文本文件。

import os

from subprocess import Popen, PIPE

userPrompt = """
    tell application "Finder"
      activate
      text returned of (display dialog "Enter your first name " default answer "" buttons {"Submit"})
    end tell
    """

proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)

firstname, error = proc.communicate(userPrompt)

filePath = os.path.join(os.path.expanduser('~'), 'Desktop', 'result.txt')

with open(filePath, 'w') as file:
    file.write(firstname)
  • 这利用 Popen 构造函数 shell 输出 osascript 命令,该命令本质上运行 AppleScript。
  • 目前,用户提供的输入被写入名为 results.txt 的文件,该文件保存在 Desktop 文件夹中。 os.path 模块用于确定目标文件路径。您需要根据需要进行更改。
  • 最后我们write the user input to file using open().

解决方案 B:使用 AppleScript 将用户输入保存到来自 Python 的文本文件。

另一种方法是 shell-out 利用 AppleScript 的 do shell script 命令将用户输入保存到文本文件。

在这种情况下,您的 .py 文件将如下所示:


userPrompt = """
    tell application "Finder"
      activate
      set firstname to text returned of (display dialog "Enter your first name " default answer "" buttons {"Submit"})
      do shell script "echo " & quoted form of firstname & " > ~/Desktop/result.txt"
      return firstname
    end tell
    """

proc = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)

firstname, error = proc.communicate(userPrompt)

# print(firstname)

一行写着:

do shell script "echo " & quoted form of firstname & " > ~/Desktop/result.txt"

基本上利用 shells echo 实用程序 redirect/save 用户输入到名为 results.txt 的文件,该文件再次保存到 桌面 文件夹。