2016-07-24 142 views
1

在這裏很少有AppleScript用戶,所以這可能是非常基本的東西,但我似乎無法制作一個非常簡單的腳本來創建新的別名文件工作。這是腳本的全部內容:使別名腳本失敗

set source_file to "/path/to/test.txt" 
set alias_file to "/path/to/test.txt alias" 
tell application "Finder" to make new alias at alias_file to source_file 

我試過它,沒有「新」。我用文件名前面的「POSIX文件」和文件名後面的「作爲POSIX文件」作爲強制命令來試用它。我試着用「at * to *」和「to * at *」。以防萬一目的地需要成爲一個包含的文件夾我已經嘗試過了。絕對所有的變化產生相同的錯誤信息:

execution error: Finder got an error: AppleEvent handler failed. (-10000) 

這並沒有告訴我很多。

我明顯地用「/ path/to /」替換了實際的文件路徑,但我可以保證ls /path/to/test.txt確認源路徑有效,並且ls "/path/to/test.txt alias"確認目標路徑不存在。

萬一它很重要,我運行Mac OS X 10.11.5。爲make的Finder.sdef進入肯定看起來像它應該做我想做的:

make v : Make a new element make 

new type : the class of the new element 

at location specifier : the location at which to insert the element 

[to specifier] : when creating an alias file, the original 
    item to create an alias to or when creating a file viewer window, 
    the target of the window 

[with properties record] : the initial values for the properties of 
    the element → specifier : to the new object(s) 

我真正想要做的是用命令行osascript和我真的,真的要執行這個要做的是從Python調用osascript單線程,所以文件路徑將是內聯的,而不是變量。但是我首先移動到命令行,然後移動到腳本編輯器,因爲我無法使其工作,並且每個調用此代碼片段的方法都會產生相同的錯誤消息。所以希望當/如果我得到一個腳本的工作,我將能夠從Python的osascript調用等效的代碼。 :}

回答

2

你肯定是在正確的軌道上使用POSIX file因爲AppleScript represents file paths differently than POSIX does(本質上,冒號而不是正斜槓)。

您可以手動將所有路徑轉換爲AppleScript路徑,但爲了保持文件路徑的可讀性(並且讓讀者知道它們確實是文件的源代碼),我認爲將它們轉換爲更好的解決方案路徑)。

但是,POSIX file的問題在於它返回文件引用,而不是make new alias命令正在查找的文本路徑。爲了解決這個問題,所有你需要做的就是投返回的文件引用作爲text使alias開心:

set source_file to (POSIX file "/path/to/test.txt") as text 
set alias_file to (POSIX file "/path/to/test.txt alias") as text 
tell application "Finder" to make new alias at alias_file to source_file 

還有一個問題,雖然:在make new alias at x to y命令期望y是一個文件和x路徑成爲別名應該放置的目錄的路徑,但是您要將文件的路徑傳遞給xy。目標(「at」)路徑應該是/path/to/ - make new alias命令將自動命名別名{original filename} alias。所以,總結:

set source_file to (POSIX file "/path/to/test.txt") as text 
set alias_dir to (POSIX file "/path/to/") as text 
tell application "Finder" to make new alias at alias_dir to source_file 

這可能有點冗長,但我希望它有幫助!

+1

它非常有幫助。解決方法和原因。謝謝! – larryy

+0

@larryy太棒了!很高興我能幫上忙。 – AstroCB

+1

更正:1.冒號分隔的HFS路徑是舊的OSX之前的宿醉。AS支持那些向後兼容(和AS AS開發者是懶惰的),並且還支持標準的POSIX路徑。 2. Finder期望_object說明符_(例如home文件夾中的「文件」文件的'file「test.txt文件),但會在大部分用例中接受HFS路徑字符串(Finder也是舊的OSX之前的宿醉)或」別名「 /'POSIX文件'說明符並轉換它們; 'get'和'set'是例外。 3. HFS路徑基本上存在缺陷 - 它們無法區分名稱相同的卷 - 因此請儘可能使用POSIX路徑。 – foo