我在python应用程序中使用Apple脚本,如何将用户提供的输入保存为文本文件?
firstname = """
display dialog "Enter your first name " default answer "" ¬
buttons {"Submit"}
"""
答案 0 :(得分:1)
请考虑以下任一解决方案:
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
构造函数来封装实际上运行AppleScript的osascript
命令。results.txt
的文件,该文件将保存到 Desktop 文件夹中。 os.path
模块用于确定目标文件路径。您需要根据需要对此进行更改。open()
。另一种方法是利用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"
基本上利用shell echo
实用程序将用户输入重定向/保存到名为results.txt
的文件中,该文件再次保存到 Desktop 文件夹中。