如何为流程设置环境变量?

时间:2016-12-15 17:20:21

标签: process swift3 environment-variables

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")

不幸的是,结果和以前一样。

1 个答案:

答案 0 :(得分:4)

您只需将Process的{​​{3}}变量设置为包含变量的[String: String]值映射。

let process = Process()
// ...
process.environment = ["home": "/Users/foo"]

如果您想传递当前环境,可以这样做:

let process = Process()
// ...
let environment = ProcessInfo.processInfo.environment
environment["home"] = "/Users/foo" //optionally set new vars, or overwrite old ones
process.environment = environment

如果要设置工作目录,这不是由环境变量决定的,而是通过environment

let process = Process()
// ...
process.currentDirectoryPath = "/Users"