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

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

问题描述

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

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!

示例:在给定〜/音乐/不存在"的情况下,它将切换到用户主文件夹中的音乐"文件夹,然后如果有的话,在底层窗口的默认文本字段中键入"不存在".

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 Event的费用更高:

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天全站免登陆