Applescript 可以用来判断目录(路径)是否存在? [英] Can Applescript be used to tell whether or not a directory (path) exists?

查看:49
本文介绍了Applescript 可以用来判断目录(路径)是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 Applescript 代码,可以通过 KEYSTROKE 将路径切换到转到"对话框中来切换到指定目录.

I've got some Applescript code that switches to a specified directory by KEYSTROKEing the path into the "Go To" dialog.

遗憾的是,如果请求的目录不存在,此对话框不会引发错误?!它只是沿着路径走得尽可能远,然后将不存在的路径片段转储到它下面的任何窗口的默认文本字段中

Regretfully, this dialog does NOT raise an error if the requested directory does not exist?! It just goes as far as it can along the path and then DUMPS THE NONEXISTENT PATH FRAGMENT into the default text field of whatever window is under it!

示例:给定~/Music/nonexistent",它将切换到用户主文件夹中的 Music 文件夹,然后在底层窗口的默认文本字段中键入"nonexistent"(如果有).

Example: given "~/Music/nonexistent" it would switch to the Music folder in the user's home folder then 'type' "nonexistent" into the underlaying window's default text field if it has one.

因此,我需要知道如何从 Applescript 中找出给定路径是否已经存在.

Consequently, I need to know how to find out if a given path already exists or not from Applescript.

推荐答案

在 AppleScript 中,您可以通过将路径强制转换为 alias 说明符来简单地检查路径是否存在.如果路径不存在,则抛出错误

In AppleScript you can simply check if a path exists by coercing the path to an alias specifier. If the path does not exist an error is thrown

此外,您必须以编程方式扩展波浪号.处理程序返回一个布尔值.

Further you have to expand the tilde programmatically. The handler returns a boolean value.

on checkPathExists(thePath)
    if thePath starts with "~" then set thePath to POSIX path of (path to home folder) & text 3 thru -1 of (get thePath)
    try
        POSIX file thePath as alias
        return true
    on error
        return false
    end try
end checkPathExists

set pathisValid to checkPathExists("~/Music/nonexistent")

或者使用 System Events,但发送 Apple Events 会贵一些:

Alternatively use System Events, but sending an Apple Event is a bit more expensive:

set thePath to "~/Music/nonexistent"
tell application "System Events" to set pathisValid to exists disk item thePath

这篇关于Applescript 可以用来判断目录(路径)是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆