如何编写像Top这样的交互式程序?
How to write interactive program like Top?
当您 运行 top 时,您进入了终端中的交互式显示,但命令行消失了。
我想用这种类型的显示构建一个程序,但不知道要研究什么。
- 我从哪里开始?
top
刚发布的时候用的是curses,后来因为curses的开销改用自己的屏幕管理代码。
更多关于top的内容可以在下面link阅读:
总的来说,您要查找的内容属于 TUI(基于文本的用户界面)类别。
大多数情况下,ncurses 是针对想要在终端中合并 "graphics" 的文本表示的人的 goto 推荐。
但是有几种不同的选择,我建议 google 找到适合您使用的库。首先,您查看下面列出的 links:
出于教育目的,我提出了一个不完美但可用的程序,它可以捕获 bash 中的箭头键并立即响应它们:
#!/bin/bash
# Put terminal into canonical mode with noecho
# (not required for this example but perhaps useful nonethless )
MYTERMRESTORE=$(stty --save)
stty icanon -echo
# Obtain terminal dimensions
columns=$(tput cols)
lines=$(tput lines)
# Populate a buffer and store its size
buffer="$(ps aux)"
scroll="${#buffer}"
# Set a top bar and scrolling region (printf "3[2;${lines}")
tput csr 1 "${lines}"
while [ "${#x}" -lt "$columns" ]
do x="$x="
done
printf "$x\n"
# Set up a continuos loop
while [ 1 ]
do printf "%.*s" $scroll "$buffer"
printf "\n\nUse arrow keys to toggle through output, q to quit\n"
read -n 1 i
case "$i" in
'[')
read -n 1 j
case "$j" in
"A") # Up arrow
scroll=$(( scroll - $columns ))
;;
"B") # Down arrow
scroll=$(( scroll + $columns ))
;;
esac
;;
'q') break
;;
esac
done
stty "$MYTERMRESTORE"
也许这个程序需要的最直接的改进是一种持续更新缓冲区的机制。在具有异步多路复用用户输入的程序中,这通常使用 select()
.
来完成
当您 运行 top 时,您进入了终端中的交互式显示,但命令行消失了。
我想用这种类型的显示构建一个程序,但不知道要研究什么。
- 我从哪里开始?
top
刚发布的时候用的是curses,后来因为curses的开销改用自己的屏幕管理代码。
更多关于top的内容可以在下面link阅读:
总的来说,您要查找的内容属于 TUI(基于文本的用户界面)类别。
大多数情况下,ncurses 是针对想要在终端中合并 "graphics" 的文本表示的人的 goto 推荐。
但是有几种不同的选择,我建议 google 找到适合您使用的库。首先,您查看下面列出的 links:
出于教育目的,我提出了一个不完美但可用的程序,它可以捕获 bash 中的箭头键并立即响应它们:
#!/bin/bash
# Put terminal into canonical mode with noecho
# (not required for this example but perhaps useful nonethless )
MYTERMRESTORE=$(stty --save)
stty icanon -echo
# Obtain terminal dimensions
columns=$(tput cols)
lines=$(tput lines)
# Populate a buffer and store its size
buffer="$(ps aux)"
scroll="${#buffer}"
# Set a top bar and scrolling region (printf "3[2;${lines}")
tput csr 1 "${lines}"
while [ "${#x}" -lt "$columns" ]
do x="$x="
done
printf "$x\n"
# Set up a continuos loop
while [ 1 ]
do printf "%.*s" $scroll "$buffer"
printf "\n\nUse arrow keys to toggle through output, q to quit\n"
read -n 1 i
case "$i" in
'[')
read -n 1 j
case "$j" in
"A") # Up arrow
scroll=$(( scroll - $columns ))
;;
"B") # Down arrow
scroll=$(( scroll + $columns ))
;;
esac
;;
'q') break
;;
esac
done
stty "$MYTERMRESTORE"
也许这个程序需要的最直接的改进是一种持续更新缓冲区的机制。在具有异步多路复用用户输入的程序中,这通常使用 select()
.