Перевод кода из BASH в python: отзыв команды и история - PullRequest
0 голосов
/ 28 октября 2018

У меня есть 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» в файл истории.Тогда мне просто нужно побеспокоиться об отзыве команд.

Есть ли хороший и простой "pythonic" способ сделать то, что делает скрипт BASH?

Спасибо.

1 Ответ

0 голосов
/ 28 октября 2018

Использование https://docs.python.org/3.5/library/readline.html. Роллинг, вероятно, не стоит усилий.

...