2017-06-19 44 views
1

在使用Swift進程運行MySQL恢復轉儲文件時遇到問題。如何使用標準輸入在Swift 3.0中運行進程

let command = "/usr/local/bin/mysql -h theHost -P 3306 -u root -pTheInlinePassword example_database < dumpFile.sql" 
    let task = Process() 
    task.launchPath = "/usr/bin/env" 
    task.arguments = command.components(separatedBy: " ") 
    task.launch() 

問題是過程不理解標準輸入<。我如何用像這樣的標準輸入來運行命令。謝謝。

更新:

let task = Process() 
    task.launchPath = "/usr/local/bin/mysql" 
    task.arguments = ["-h", "theHost", "-P", "3306", "-u", "root", "-pTheInLinePassword", "example_data"] 
    task.standardInput = try! FileHandle(forReadingFrom: filePath!) 
    task.launch() 

我試過代碼波紋管。這適用於我

回答

2

< filename語法是shell提供的功能,不是程序自己處理的東西。

來處理這個正確的方法是建立一個FileHandledumpFile.sql閱讀,然後設置了ProcessFileHandle作爲standardInput財產。

作爲一個方面說明,我不知道爲什麼你使用/usr/bin/env爲您啓動的路徑,因爲你不依賴於PATH查找或設置任何環境變量。

let input = try FileHandle(forReadingFrom: URL(fileURLWithPath: "dumpFile.sql")) 
let task = Process() 
task.launchPath = "/usr/bin/mysql" 
task.arguments = ["-h", "theHost", "-P", "3306", "-u", "root", "-pTheInlinePassword", "example_database"] 
task.standardInput = input 
task.launch() 
+0

或'文件句柄(forReadingAtPath:「dumpFile.sql」)' –

+0

你可以使用過,雖然它返回'nil'如果不存在該文件,而URL版本拋出一個錯誤。所以如果你使用字符串版本,確保你處理'nil'值。 –

+0

謝謝凱文和馬丁,我現在試試 – Max

相關問題