У меня есть BASH-скрипт, который является реализацией псевдотерминала. Весь скрипт эмулирует ввод и запуск команд во встроенной операционной системе на другом устройстве.
Вот функция, которая представляет пользователю запрос и принимает ввод:
function mterm
{
# Interactive psuedo-terminal for sending commands to stbox.
#
# An endless loop prompts user for input.
# The prompt displayed is the IP address of the target and '>'.
# Commands consisting of pipes (|) and redirects (>) are parsed
# such that the first command is sent to "parsecommand" function,
# and the output of that function is piped or redirected to the
# remaining items on the command line which was entered by the
# user at the prompt.
#
# The commands entered by the user at the prompt are saved
# in a "history" file defined by the HIST* variables below. The
# user should be able to recall previous commands (and edit them
# if desired) by using the arrow keys.
export HISTFILE=~/.gsi_history
export HISTTIMEFORMAT="%d/%m/%y %T "
export HISTCONTROL=ignoreboth:erasedups
export HISTSIZE=10000
export HISTFILESIZE=100000
history -r ${HISTFILE}
while read -ep "${1}> " CMD
do
history -s "${CMD}"
s="[|>]"
if [[ ${CMD} =~ ${s} ]]
then
CMD1=${CMD%%[>|]*}
CMD2=${CMD#${CMD1}}
CMD1=$(echo ${CMD1}|xargs) # To remove any leading or training whitespaces.
eval "parsecommand \"${CMD1}\"${CMD2}"
else
parsecommand "${CMD}"
fi
done
history -w ${HISTFILE}
}
Я пытаюсь сделать что-то подобное в python. Вот что я имею до сих пор:
#!/usr/bin/python
import sys
import signal
import time
def handler(signum, frame):
print "Exiting"
exit(0)
signal.signal(signal.SIGINT, handler)
f=sys.stdin
while 1:
print "> ",
CMD=f.readline()
if not CMD: break
print("CMD: %s" % CMD)
Это работает. Он принимает входные команды и выводит то, что было напечатано. Поэтому "CMD" можно передать другой функции для ее анализа. Если набирается CTRL-D, он заканчивается, как и BASH-скрипт.
Однако, как и скрипт BASH, мне бы хотелось, чтобы файл истории и команда возвращались (используя стрелку вверх, конечно).
Полагаю, я мог бы просто вручную добавлять "CMD" в файл истории каждый раз. Тогда мне просто нужно будет беспокоиться о вызове команды.
Есть ли хороший и простой "питонический" способ сделать то, что делает скрипт BASH?
Благодарю.
Используйте https://docs.python.org/3.5/library/readline.html. Роллинг, вероятно, не стоит усилий.