我尝试使用Swift创建终端仿真器,到目前为止我已经获得了所有基本功能。我可以发送diskutil list
之类的命令并获得正确的输出。但是,如果我要求程序在任何方面都是交互式的,例如用户必须指定密码的sudo reboot
,我会收到错误sudo: no tty present and no askpass program specified
;或者当我想使用nano anyTextFile.txt
时,我会收到类似Error opening terminal: unknown.
的错误,我在Process
类中看不到与指定有关的任何内容TTY或askpass(无论是什么)
这里的代码应与此问题相关:
func shell(_ args: String) -> (output: [String], error: [String], exitCode: Int32) {
var output : [String] = []
var error : [String] = []
let task = Process()
task.launchPath = "/usr/bin/env"
let cmd = args.characters.split(separator: " ").map(String.init)
task.arguments = cmd
let outpipe = Pipe()
task.standardOutput = outpipe
let errpipe = Pipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
output = string.components(separatedBy: "\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: errdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
error = string.components(separatedBy: "\n")
}
task.waitUntilExit()
let status = task.terminationStatus
return (output, error, status)
}