【问题标题】:AppleScript: String and File ManpiulationAppleScript:字符串和文件操作
【发布时间】:2012-04-13 21:03:12
【问题描述】:

使用 mdfind() 脚本收集文件列表后,我现在需要复制找到的每个文件并存储它们的原始路径以供以后使用。从本质上讲,我必须将大量且广泛分布的旧 AppleWorks 文件移动到新卷中,手动更新它们,然后用新的更新版本替换原始文件在相同的位置并使用相同的文件名 em>(但不是扩展名或文档类型)。

由于我是 AppleScript 新手,我正在使用 Python 进行文件操作,并且仅使用 AppleScript 来定位文档(因为文件扩展名不足以满足我的目的,我需要通过 mdfind 查看苹果元标记)。

但是我可以使用 AppleScript 生成的文档(文件路径列表)使用苹果“\r”换行符,因此我无法轻松将其导入 python。

我的苹果脚本:

set the_script to "mdfind   kMDItemKind=='*AppleWorks*'"
set the_text to (do shell script the_script)
set the_doc to (choose file)
write the_text to the_doc

这会生成一个包含各种可爱路径名的 .txt 文件,但 python 将其读取为一个巨大的字符串。

我该怎么做

a) 告诉 Apple Script 将自定义分隔符附加到每一行(即“\n”)

b) 我如何告诉 Apple Script 将找到的每个文件复制到新位置,同时保留原始文件并记录其路径?

任何帮助将不胜感激。

更新@Kindall

这是当我尝试在mdfind 命令中使用管道时python 抛出的错误:

 File "<stdin>", line 1, in <module>
 File     "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
 File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

有什么想法吗?我主要是一名网络开发人员,试图通过其他一些语言来避免手动排序我老板古老的 mac 笔记本电脑上的 2-3k 文件,哈哈(我纠正了你原始代码中的印刷错误,我不是想逐字运行)。

【问题讨论】:

  • 尝试用-e分隔行

标签: python file-io applescript


【解决方案1】:

(c):用 Python 读完文件后,将文件内容拆分到 '\r' 上怎么样?

【讨论】:

  • Python 无法识别 Apple 的“\r”分隔符,唉。
  • Python 实际上应该 -- 我假设 Apple 提供的 Python 解释器编译时支持通用换行符,在这种情况下,字符串上的简单 .splitlines() 应该可以解决问题。
  • 你不能在恰好是 '\r' 的字符上显式拆分字符串吗?
  • 谢谢,我是一个 python 小块,.splitlines() 工作得很好,我只是一个小块,henh,尽管最终上面的纯 python 解决方案比其他任何东西都更适合我。感谢大家的投入!
【解决方案2】:

如何(d):在 Python 中执行 mdfind

import subprocess

command = "mdfind kMDItemKind=='*AppleWorks*'"
subpipe = subprocess.Popen(command, stdout=subprocess.PIPE)
outlist = subpipe.communicate()[0].splitlines()

for filename in outlist:
    print filename    # or whatever

注意:我目前实际上不在 Mac 上,但这对我来说在 Windows 和 dir C:\ comamand 上运行良好,所以它应该在带有 mdfind 的 Mac 上运行良好。

【讨论】:

  • 嗯,我立刻喜欢上了这个解决方案——我对 AppleScript 并不是很感兴趣,但是 python 会抛出一个错误。我已将代码作为对我最初问题的编辑包含在内,请参见上文(感谢您的输入)。
【解决方案3】:

根据 Kindall 的建议,我和我实验室的一些人提出了一个适用于 Apple 但完全使用 python 的解决方案,如下所示:

import os
import subprocess

outfile = os.open("test",os.O_CREAT)
os.close(outfile)
outfile = os.open("test",os.O_RDWR)
command = ["mdfind","kMDItemKind == '*AppleWorks*'"]
subpipe = subprocess.Popen(command, stdout=outfile)

这会在运行脚本的目录中生成一个文本文件。感谢各种建议。

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多