我想讀一個URL的內容同步在斯威夫特一個簡單的命令行批處理腳本。爲了簡單起見,我使用了cURL - 如果必須的話,我知道我可以使用NSURLSession。我也使用OSX上Swift的開源版本swift build
來構建它。捲曲通過NSTask不會終止,如果管道出現
的問題是,在某些URL時,NSTask永遠不會終止,如果stdout已經被重定向到一個管道。
// This will hang, and when terminated with Ctrl-C reports "(23) Failed writing body"
import Foundation
let task = NSTask()
let pipe = NSPipe()
task.launchPath = "/usr/bin/curl"
task.arguments = ["http://trove.nla.gov.au/newspaper/page/21704647"]
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
但是,如果您刪除管道或更改URL,任務將成功。
// This will succeed - no pipe
import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/curl"
task.arguments = ["http://trove.nla.gov.au/newspaper/page/21704647"]
task.launch()
task.waitUntilExit()
// This will succeed - different URL
import Foundation
let task = NSTask()
let pipe = NSPipe()
task.launchPath = "/usr/bin/curl"
task.arguments = ["http://trove.nla.gov.au/newspaper/page/21704646"]
task.standardOutput = pipe
task.launch()
task2.waitUntilExit()
運行的任何直接使用curl從終端成功的例子,所以有一些事情與NSTask的互動,從特定的URL檢索時(和其他幾個人),並在管道存在,那導致cURL失敗。
愚蠢的問題;但是你確定你想在這裏使用「let」而不是「var」。如果任務產生輸出,它是否被賦值回變量本身? – user3069232
對於管道,你的意思是?輸出被傳遞到可讀取的管道。輸出不會替代NSPipe實例本身。 – tobygriffin
好的,但我在代碼中看不到「var」,只是「let」;沒有東西被傳回給任何東西? – user3069232