從How do I run an terminal command in a swift script? (e.g. xcodebuild)複製:你如何爲一個過程設置環境變量?
import Foundation
@discardableResult
func 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")
這看起來整潔。我只是想知道如何設置$PWD
這樣的環境變量(在這裏命名爲task
......)。
我試過如下:
import Foundation
@discardableResult
func execCommand(_ args: String...) -> Int32 {
let process = Process()
process.launchPath = "/usr/bin/env"
process.environment = ["PWD": "/Users"]
if let env = process.environment {
print(env["PWD"] ?? "Unknown")
} else {
print("Environment not available!")
}
process.arguments = args
process.launch()
process.waitUntilExit()
return process.terminationStatus
}
execCommand("pwd")
,並得到這些線路印刷:
/Users
/private/tmp/AppIcon.appiconset
顯然,環境變量已定,但對pwd命令沒有任何影響。
另一種方法:
import Foundation
@discardableResult
func execCommand(_ args: String...) -> Int32 {
let process = Process()
process.launchPath = "/usr/bin/env"
var environment = ProcessInfo.processInfo.environment
environment["PWD"] = "/Users" //optionally set new vars, or overwrite old ones
process.environment = environment
if let env = process.environment {
print(env["PWD"] ?? "Unknown")
} else {
print("Environment not available!")
}
process.arguments = args
process.launch()
process.waitUntilExit()
return process.terminationStatus
}
execCommand("pwd")
不幸的是相同的結果之前。
https://developer.apple.com/reference/foundation/process/1409412-environment – Alexander
你不應該叫'Process'實例的'task'。 'NSTask'已被重新命名。 – Alexander