当我尝试为使用 system_profiler 命令检索系统软件和硬件详细信息的应用程序创建帮助程序时,出现以下错误。
Response from XPC service: HELLO XPC
Response from XPC service: /usr/sbin/system_profiler: /usr/sbin/system_profiler: cannot execute binary file"
代码如下。
class CommandHelper: NSObject,CommandHelperProtocol {
func upperCaseString(_ string: String, withReply reply: @escaping (String) -> Void) {
let response = string.uppercased()
reply(response)
}
func loadServerURL(_ string: String, withReply reply: @escaping (String) -> Void) {
let pipe = Pipe()
let process = Process()
process.launchPath = "/bin/sh"
process.arguments = ["system_profiler","SPHardwareDataType"]
process.standardOutput = pipe
process.standardError = pipe
let fileHandle = pipe.fileHandleForReading
process.launch()
let response = String(data: fileHandle.readDataToEndOfFile(), encoding: .utf8)
print(response!)
reply(response!)
}
}
当我将 launchPath 设置为/usr/sbin/system_profiler 时,我得到空白输出。
最佳答案
Shell 执行脚本,而不是二进制文件。解决办法是直接运行该工具;几乎没有任何理由仅仅为了执行程序而启动 shell:
process.launchPath = "/usr/sbin/system_profiler"
process.arguments = ["SPHardwareDataType"]
此外,如果您不打算使用 stderr
管道,那么设置它是没有意义的:
/* process.standardError = pipe */
关于Swift-创建助手时发现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53444585/