gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:01:41 25 4
gpt4 key购买 nike

复制自 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")

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

最佳答案

您只需设置 environment Process 的变量到包含变量到值映射的 [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

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

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

关于process - 如何为进程设置环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com