[英]Swift shell command returns empty result
I have installed chrome-cli in my Mac.我在我的 Mac 上安装了chrome-cli 。 I'm trying to execute chrome-cli commands from Swift with following code:我正在尝试使用以下代码从 Swift 执行 chrome-cli 命令:
import Foundation
func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/bash"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
// Example 1:
let example1 = shell("/usr/local/bin/chrome-cli --help") //returns expected result
let example2 = shell("/usr/local/bin/chrome-cli list tabs") // return ""
Here, example 1 is calling with single argument and works well, ie it print same result like we execute the command in Terminal.在这里,示例 1 使用单个参数调用并且运行良好,即它打印与我们在终端中执行命令相同的结果。
but for example 2, we have more than 1 argument and it always returns empty result.但是对于示例 2,我们有不止 1 个参数,它总是返回空结果。 While the same command on Terminal print list of tab currently opened.在当前打开的选项卡的终端打印列表上使用相同的命令。
I think the process doesn't wait for command to return the result as it takes 1-2 seconds to list tabs in Terminal app.我认为该过程不会等待命令返回结果,因为在终端应用程序中列出选项卡需要 1-2 秒。 or its some other issue?还是其他问题?
Please help.请帮忙。 Thanks.谢谢。
Since chrome-cli 1.6.0 was released in 2018 but new Chrome versions with new features appear regularly I suggest to use Chrome directly via SBApplication
to access to any needed info eg:由于 chrome-cli 1.6.0 于 2018 年发布,但具有新功能的新 Chrome 版本经常出现,我建议直接通过SBApplication
使用 Chrome 来访问任何需要的信息,例如:
import ScriptingBridge
@objc protocol ChromeTab {
@objc optional var id: Int {get}
@objc optional var title: String {get}
}
extension SBObject: ChromeTab {}
@objc protocol ChromeWindow {
@objc optional var tabs: [ChromeTab] {get}
}
extension SBObject: ChromeWindow {}
@objc protocol ChromeApplication {
@objc optional var windows: [ChromeWindow] {get}
}
extension SBApplication : ChromeApplication {}
// Print all tabs
if let chrome = SBApplication(bundleIdentifier: "com.google.Chrome") as ChromeApplication? {
if let window = chrome.windows?.first {
window.tabs?.forEach {
if let id = $0.id, let title = $0.title {
print("[\(id)] -", title)
}
}
}
}
For more info about Chrome Extensions look at https://developer.chrome.com/extensions/devguide有关 Chrome 扩展的更多信息,请访问https://developer.chrome.com/extensions/devguide
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.