gpt4 book ai didi

python - BASH 到 python 代码翻译 : command recall and history

转载 作者:太空宇宙 更新时间:2023-11-03 21:39:00 25 4
gpt4 key购买 nike

我有一个 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 脚本的操作?

谢谢。

最佳答案

使用https://docs.python.org/3.5/library/readline.html 。自己推出可能不值得付出努力。

关于python - BASH 到 python 代码翻译 : command recall and history,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53028258/

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