我需要为xcode启动一个终端命令。 这是命令:
sudo xattr -d -r com.test.exemple /Desktop/file.extension
我试过了
let task = Process()
task.launchPath = "/usr/sbin/xattr"
task.arguments = ["-d","-r", "com.test.exemple"," /Desktop/file.extension"]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output : String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
print(output)
答案 0 :(得分:1)
这是使用命令之间的管道来实现它的一种方法。我验证了当我在注释掉的行中使用参数时,文件由超级用户创建。
它正在做的是:
echo'password'| sudo -S / usr / bin / xattr -d -r com.test.exemple /Desktop/file.extension
{{1}}
答案 1 :(得分:1)
我在阅读这篇较新的 question 后遇到了这个问题。以防万一有人通过搜索到达这里,这里是我的 answer 到该问题的代码。
实际上没有必要通过 echo
进行管道传输;以下工作正常:
以下更直接的方法经过测试并有效:
import Foundation
let password = "äëïöü"
let passwordWithNewline = password + "\n"
let sudo = Process()
sudo.launchPath = "/usr/bin/sudo"
sudo.arguments = ["-S", "/bin/ls"]
let sudoIn = Pipe()
let sudoOut = Pipe()
sudo.standardOutput = sudoOut
sudo.standardError = sudoOut
sudo.standardInput = sudoIn
sudo.launch()
// Show the output as it is produced
sudoOut.fileHandleForReading.readabilityHandler = { fileHandle in
let data = fileHandle.availableData
if (data.count == 0) { return }
print("read \(data.count)")
print("\(String(bytes: data, encoding: .utf8) ?? "<UTF8 conversion failed>")")
}
// Write the password
sudoIn.fileHandleForWriting.write(passwordWithNewline.data(using: .utf8)!)
// Close the file handle after writing the password; avoids a
// hang for incorrect password.
try? sudoIn.fileHandleForWriting.close()
// Make sure we don't disappear while output is still being produced.
sudo.waitUntilExit()
print("Process did exit")
关键是你必须在密码后添加一个换行符。