うぃくとです。
この記事はApple Scriptでカレントディレクトリを取得してGUI表示するまでの続きです。7年後に自分が読み返してもわかるように書きます。
はじめに
やることの概要を確認
- ファイルを新規作成してカレントディレクトリの値を本文に書き込みます
- 前回の内容と被る部分は省略します
前提となる知識と具体例
前回までの知識をフルパワー動員して次のようなコードを開発します。
tell application "Finder"
set aCurrentPath to folder of (path to me) as Unicode text
set aPosixCurrentPath to get POSIX path of aCurrentPath
end tell
display dialog ¬
{"カレントディレクトリにファイルを作成してもよいですか?", "
", aPosixCurrentPath} as Unicode text ¬
default button "OK" with title "確認ダイアログ" as string
ファイルを新規作成する
ファイルを新規に作成する方法はいくつかあります。echo 本文 > ファイル名をシェルスクリプトとして実行するのがいまのところ最も簡単そうですので、この方法を使います。
writeを用いる方法では既存ファイルをオープンする必要があり、ファイルを新規作成するという準備ステップが必要になります。それほど難しいことではないですが、今回はよりかんたんに仕上げることに重点をおいてすすめるため使いません。
文字列を作る
開発したのは次のようなコードです。
set fileContents to {"echo \"", aCurrentPath, "\n", aPosixCurrentPath, "\n\n made by fileIO.app \""} as Unicode text
カレントディレクトリをHFSとPOSIXでそれぞれ表現したパスを書き込みます。
またこのスクリプトで自動生成したことを示すために簡単な署名も書き込みます。
なお一度実行したソースコードは、\n が 改行に置き換わり次のようになります。
set fileContents to {"echo \"", aCurrentPath, "
", aPosixCurrentPath, "
made by fileIO.app \""} as Unicode text
シェルを実行する
実装したのは次のようなコードです。ファイルの保存先はPOSIX表現で指示します。
set doShell to {fileContents, " > ", aPosixCurrentPath, "/currentDir_doShellScript.txt"} as Unicode text
do shell script doShell
次のように、ターミナル(Terminal)を起動してコマンドラインを実行するという手もあります。
set cmdln to {fileContents, " > ", aPosixCurrentPath, "/currentDir_tellApplicationTerminal.txt"} as Unicode text
tell application "Terminal"
run
do script cmdln
delay 0.03125
quit
end tell
tell application〜end tellでは、アプリケーション(ここではターミナル)に対して指示をすることを宣言します。runでアプリケーションを起動させます。do scriptは指定したスクリプトを実行します。
起動したアプリケーションは明示的に終了させる必要があります。ただコマンドラインが完了しないうちにその実行基盤となっているアプリケーション(ここではTerminal)を終了させてします恐れがあります。
そこでdelayで指定した秒数だけ待つことで、コマンドライン実行完了後にアプリケーションをquitするように調整しています。
まとめ
-- get current directory path
tell application "Finder"
set aCurrentPath to folder of (path to me) as Unicode text
set aPosixCurrentPath to get POSIX path of aCurrentPath
end tell
-- confirmation
display dialog ¬
{"カレントディレクトリにファイルを作成してもよいですか?", "\n", aPosixCurrentPath} as Unicode text ¬
default button "OK" with title "確認ダイアログ" as string
-- create strings
set fileContents to {"echo \"", aCurrentPath, "\n", aPosixCurrentPath, "\n\n made by fileIO.app \""} as Unicode text
-- do shell script
set doShell to {fileContents, " > ", aPosixCurrentPath, "/currentDir_doShellScript.txt"} as Unicode text
do shell script doShell
-- do shell script via Terminal
set cmdln to {fileContents, " > ", aPosixCurrentPath, "/currentDir_tellApplicationTerminal.txt"} as Unicode text
tell application "Terminal"
run
do script cmdln
delay 0.03125
quit
end tell


コメント