问题描述
在我正在处理的程序中,我需要执行交互式的命令行程序。为此,我使用Process调用带有标准输入和标准输出管道的命令。
这很好用,但是我不知道如何检测进程何时请求用户输入,以便我可以要求命令输出处理器提供它。
这是我创建流程的方式:
self.process.arguments = /* arguments */
self.process.launchPath = /* launch path */
let input = Pipe()
let output = Pipe()
self.process.standardInput = input
self.process.standardOutput = output
self.input = input
self.output = output
这是我开始/收听过程的方式:
self.process.terminationHandler = { [weak self] process in
// Handle termination
}
process.launch()
observation = NotificationCenter.default.addObserver(
forName: .NSFileHandleDataAvailable,object: self.output.fileHandleForReading,queue: queue,using: { [weak self] notification in
guard let strongSelf = self else {
return
}
let handle = notification.object as! FileHandle
// Read and process output from `handle`
handle.waitForDataInBackgroundAndNotify()
}
)
output.fileHandleForReading.waitForDataInBackgroundAndNotify()
并且在必要时,我可以使用以下命令将输入发送回流程:
self.input.fileHandleForWriting.write(input.data(using: .utf8) ?? Data())
非常感谢您的帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)