[英]Running shell commands in Swift
我正在嘗試在我的OSX應用程序中使用Swift運行shell命令。
運行echo之類的基本命令可以正常運行,但是后續拋出
“env:node:沒有這樣的文件或目錄”
@IBAction func streamTorrent(sender: AnyObject) {
shell("node", "-v")
}
func shell(args: String...) -> Int32 {
let task = NSTask()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
運行系統命令時,我也會收到“sh:node:command not found”。
system("node -v")
更新:
不像下面的一些建議那么好,但我設法將命令回顯到一個文件中並在終端中打開並執行:
system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")
func shell(command: String) -> Int32 {
let task = NSTask()
task.launchPath = "/usr/bin/env"
task.arguments = ["bash", "-c", command]
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
所以你可以做shell("node -v")
,我覺得更方便:
再看看這個。
nodejs
安裝程序使用/usr/local/bin
,它不包含在從Finder啟動的應用程序的PATH
中:
/usr/bin:/bin:/usr/sbin:/sbin
該目錄通過/etc/profile
& path_helper包含在bash
的PATH
集中:
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
選項:
“sh:node:command not found”
顯然, node
不是絕對路徑。
聽起來你已經對~/.bash_profile
或其他文件進行了更改,以在PATH
環境變量中包含node
的位置。
system
正在使用sh -c
啟動bash
。
我忘了規則是什么,但是bash
在執行這種方式時會忽略至少一些配置文件。 據推測,您對PATH
的更改未被閱讀或應用。
“env:node:沒有這樣的文件或目錄”
同樣, node
不是絕對路徑。 NSTask
不使用shell,因此您執行的任何進程都將繼承應用程序的環境變量。 在大多數情況下,這意味着默認PATH
。
如果您需要NSTask
的自定義環境, NSTask
從NSProcessInfo
獲取environment
字典,進行更改然后設置NSTask
的environment
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.