gpt4 book ai didi

bash - 在后台处理用户输入

转载 作者:行者123 更新时间:2023-11-29 09:04:01 24 4
gpt4 key购买 nike

我想处理用户输入,但在后台,就像在新线程中一样。

例如,显示进度条,当用户点击 R 时,进度条重置,或者如果用户点击 Q,脚本退出。

我不希望脚本等待用户输入。只需渲染所有内容,如果用户按下任意键,则执行某些操作。

在 bash 中可行吗?

提前致谢。

编辑:我需要脚本始终读取用户输入但不要中断主循环的执行。复杂的我用英语让自己理解

_handle_keys()
{
read -sn1 a
test "$a" == `echo -en "\e"` || continue
read -sn1 a
test "$a" == "[" || break
read -sn1 a

case "$a" in
C) # Derecha
if [ $PALETTE_X -lt $(($COLUMNS-$PALETTE_SIZE)) ] ; then
PALETTE_X=$(($PALETTE_X+1))
fi
;;
D) # Izquierda
if [ $PALETTE_X -gt 0 ] ; then
PALETTE_X=$(($PALETTE_X-1))
fi
;;
esac
}
render()
{
clear
printf "\033[2;0f BALL (X:${BALL_X} | Y:${BALL_Y})"
_palette_render # Actualiza la paleta
_ball_render
}

while true
do
LINES=`tput lines`
COLUMNS=`tput cols`

render
_handle_keys
done

在我的脚本中,只有在按下某个键时球才会移动 (render>_ball_render),因为 _handle_keys 等待用户输入。

我用 read -t0.1 做了一个丑陋的解决方案,但我不喜欢这个

PD:抱歉我最后的评论,时间编辑在我编辑的过程中完成

最佳答案

这是一种似乎有效的技术。我基于 Sam Hocevar 对 Bash: How to end infinite loop with any key pressed? 的回答.

#!/bin/bash

if [ ! -t 0 ]; then
echo "This script must be run from a terminal"
exit 1
fi

stty -echo -icanon time 0 min 0

count=0
keypress=''
while true; do
let count+=1
echo -ne $count'\r'

# This stuff goes in _handle_keys
read keypress
case $keypress in
# This case is for no keypress
"")
;;
$'\e[C')
echo "derecha"
;;
$'\e[D')
echo "izquierda"
;;
# If you want to do something for unknown keys, otherwise leave this out
*)
echo "unknown input $keypress"
;;
esac
# End _handle_keys
done

stty sane

如果 stty sane 被遗漏(例如,因为脚本被 Ctrl-C 杀死),终端将留在奇怪的状态。您可能需要查看 trap 语句来解决这个问题。

关于bash - 在后台处理用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5751718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com