我正在尝试编写交互式的swift命令行工具。其中的关键部分是具有“ writeToScreen”功能,该功能将一系列的页眉,页脚和正文作为参数,并将其很好地格式化为终端窗口的当前大小,从而将溢出状态折叠为“列表”选项。因此,该功能将类似于:
func writeToScreen(_ headers: [String], _ footers: [String], _ body: String) {
let (terminalWindowRows, terminalWindowCols) = getCurrentScreenSize()
// perform formatting within this window size...
}
func getCurrentScreenSize() -> (Int, Int) {
// perform some bash script like tput lines and tput cols and return result
}
例如,像writeToScreen(["h1","h2"], ["longf1","longf2"], "body...")
这样的输入将为相应的屏幕尺寸生成以下内容:
22x7
_ _ _ _ _ _ _ _ _ _ _ _
|(1) h1, (2) list... |
| |
| body... |
| |
| |
| |
|(3) list... |
_ _ _ _ _ _ _ _ _ _ _ _
28x7
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|(1) h1, (2) h2, (3) list...|
| |
| body... |
| |
| |
| |
|(4) longf1, (5) list... |
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
我遇到的问题是,要获取终端窗口的大小,我需要至少运行一个bash脚本,例如echo "$(tput cols)-$(tput lines)"
,它将屏幕大小输出为<cols>-<rows>
。但是,快速运行bash脚本涉及使用Process()
或NSTask()
,在我可以找到的每种使用情况下,它始终是一个单独的进程,因此,无论当前会话窗口的大小如何,它仅返回默认的终端大小。
我尝试使用:
run("tput", "cols")
(无论窗口大小如何,始终不变)我该怎么做才能获取有关当前会话的信息或在当前窗口的上下文中运行我的bash进程,特别是有关窗口大小的信息?
我曾考虑过尝试列出当前终端会话并在其中一个中运行bash脚本的方法,但是我无法弄清楚如何使之工作(类似于bash who
,然后选择正确的会话并从那里开始工作。不确定这是否可行。):https://askubuntu.com/questions/496914/write-command-in-one-terminal-see-result-on-other-one
您可以使用此功能在bash中执行命令:
func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}
然后简单地使用:
let cols = shell("tput cols")
let lines = shell("tput lines")
它将作为String返回,因此您可能希望将输出转换为Integer。
希望有所帮助。