BASH到python代码的转换:命令调用和历史记录

时间:2018-10-28 03:57:11

标签: python bash code-translation

我有一个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 :(得分:0)

使用https://docs.python.org/3.5/library/readline.html。自己动手可能不值得。