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

qed*_*qed 1 process environment-variables swift3

复制自如何在 swift 脚本中运行终端命令?(例如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")
Run Code Online (Sandbox Code Playgroud)

这看起来很整洁。我只是想知道如何$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")
Run Code Online (Sandbox Code Playgroud)

并打印了这些行:

/Users
/private/tmp/AppIcon.appiconset
Run Code Online (Sandbox Code Playgroud)

显然已经设置了环境变量,但对 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")
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*ica 6

您只需将 的environment变量设置Process[String: String]包含变量到值映射的变量。

let process = Process()
// ...
process.environment = ["home": "/Users/foo"]
Run Code Online (Sandbox Code Playgroud)

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

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

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

let process = Process()
// ...
process.currentDirectoryPath = "/Users"
Run Code Online (Sandbox Code Playgroud)