第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在swift腳本中運(yùn)行終端命令?(例如xcodebuild)

如何在swift腳本中運(yùn)行終端命令?(例如xcodebuild)

倚天杖 2019-08-26 19:23:38
如何在swift腳本中運(yùn)行終端命令?(例如xcodebuild)我想用swift替換我的CI bash腳本。我無法弄清楚如何調(diào)用普通的終端命令,如ls或xcodebuild#!/usr/bin/env xcrun swiftimport Foundation // Worksprintln("Test") // Worksls // Failsxcodebuild -workspace myApp.xcworkspace // Fails$ ./script.swift./script.swift:5:1: error: use of unresolved identifier 'ls'ls // Fails^... etc ....
查看完整描述

3 回答

?
慕工程0101907

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊

如果你不在Swift代碼中使用命令輸出,那么下面就足夠了:

#!/usr/bin/env swiftimport Foundation@discardableResultfunc shell(_ args: String...) -> Int32 {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    task.launch()
    task.waitUntilExit()
    return task.terminationStatus}shell("ls")shell("xcodebuild", "-workspace", "myApp.xcworkspace")

更新:適用于Swift3 / Xcode8


查看完整回答
反對 回復(fù) 2019-08-26
?
米琪卡哇伊

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊

如果您想在命令行中“完全”使用命令行參數(shù)(不分離所有參數(shù)),請嘗試以下操作。


(這個(gè)答案改進(jìn)了LegoLess的答案,可以在Swift 4 Xcode 9.3中使用)


func shell(_ command: String) -> String {

    let task = Process()

    task.launchPath = "/bin/bash"

    task.arguments = ["-c", command]


    let pipe = Pipe()

    task.standardOutput = pipe

    task.launch()


    let data = pipe.fileHandleForReading.readDataToEndOfFile()

    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String


    return output

}


// Example usage:

shell("ls -la")


查看完整回答
反對 回復(fù) 2019-08-26
?
長風(fēng)秋雁

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊

這里的問題是你不能混淆和匹配Bash和Swift。您已經(jīng)知道如何從命令行運(yùn)行Swift腳本,現(xiàn)在需要添加方法以在Swift中執(zhí)行Shell命令。來自PracticalSwift博客的總結(jié):

func shell(launchPath: String, arguments: [String]) -> String?{
    let task = Process()
    task.launchPath = launchPath
    task.arguments = arguments    let pipe = Pipe()
    task.standardOutput = pipe
    task.launch()

    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output = String(data: data, encoding: String.Encoding.utf8)

    return output}

以下Swift代碼將xcodebuild使用參數(shù)執(zhí)行,然后輸出結(jié)果。

shell("xcodebuild", ["-workspace", "myApp.xcworkspace"]);

至于搜索目錄內(nèi)容(這是lsBash中的內(nèi)容),我建議NSFileManager直接在Swift中使用和掃描目錄,而不是Bash輸出,這可能很難解析。


查看完整回答
反對 回復(fù) 2019-08-26
  • 3 回答
  • 0 關(guān)注
  • 2338 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號