Я пытаюсь создать командную строку, которая позволит пользователю выполнять различные функции. Например, если я набираю «scriptrun» в терминал, я хочу, чтобы он запускал функцию из другого .py-файла, а затем возвращался к терминалу (- >>). По какой-то причине, если я нахожу «scriptrun», он будет работать правильно, но если я снова нажму «enter», это приведет к повторному запуску команды. Я основываю его на CLI Turtle, который я нашел. После того, как я вхожу помощь, я хочу, чтобы показать список разделов справки только один раз, а затем, если я держать удар войти, он будет просто показать терминал, но происходит следующее !:Python CLI продолжает выполнять ту же команду?
(терминал) поможет
документированных команды (типа справка):
пока цвета Гото помощи сброса левого положения scriptrun круга вперед заголовок записи воспроизведения домой сразу отменить
(Terminal) [Здесь я просто нажать кнопку ввода, но ниже вы можете увидеть это снова вызов функции справки!]
документированные команды (типа справки):
пока цвет Гото помощь сброса левое положение scriptrun круг вперед заголовок записи воспроизведения домой сразу отменить
(терминал)
Ниже приведен пример кода, который я пытаясь найти решение:
import cmd, sys
from turtle import *
from orion_package import *
class TurtleShell(cmd.Cmd):
intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n'
prompt = '(Terminal) '
file = None
# ----- basic turtle commands -----
def do_forward(self, arg):
'Move the turtle forward by the specified distance: FORWARD 10'
forward(*parse(arg))
def do_right(self, arg):
'Turn turtle right by given number of degrees: RIGHT 20'
right(*parse(arg))
def do_left(self, arg):
'Turn turtle left by given number of degrees: LEFT 90'
left(*parse(arg))
def do_goto(self, arg):
'Move turtle to an absolute position with changing orientation. GOTO 100 200'
goto(*parse(arg))
def do_home(self, arg):
'Return turtle to the home postion: HOME'
home()
def do_circle(self, arg):
'Draw circle with given radius an options extent and steps: CIRCLE 50'
circle(*parse(arg))
def do_position(self, arg):
'Print the current turle position: POSITION'
print('Current position is %d %d\n' % position())
def do_heading(self, arg):
'Print the current turle heading in degrees: HEADING'
print('Current heading is %d\n' % (heading(),))
def do_color(self, arg):
'Set the color: COLOR BLUE'
color(arg.lower())
def do_undo(self, arg):
'Undo (repeatedly) the last turtle action(s): UNDO'
def do_reset(self, arg):
'Clear the screen and return turtle to center: RESET'
reset()
def do_bye(self, arg):
'Stop recording, close the turtle window, and exit: BYE'
print('Thank you for using Turtle')
self.close()
bye()
return True
# ----- record and playback -----
def do_record(self, arg):
'Save future commands to filename: RECORD rose.cmd'
self.file = open(arg, 'w')
def do_playback(self, arg):
'Playback commands from a file: PLAYBACK rose.cmd'
self.close()
with open(arg) as f:
self.cmdqueue.extend(f.read().splitlines())
def precmd(self, line):
line = line.lower()
if self.file and 'playback' not in line:
print(line, file=self.file)
return line
def close(self):
if self.file:
self.file.close()
self.file = None
def do_scriptrun(self, arg):
'Run the script: SCRIPTRUN'
print("Let's run this thing! :)")
scriptrun()
def parse(arg):
'Convert a series of zero or more numbers to an argument tuple'
return tuple(map(int, arg.split()))
if __name__ == '__main__':
TurtleShell().cmdloop()
Любая помощь или консультация по решению приветствуется! Спасибо! :)
Думал то же самое. То, что я закончил, - это принять cmd, изменив его как cmd2 в моем рабочем каталоге, а затем изменив оператор return для пустой строки следующим образом: 'if self.lastcmd: return []' Простое исправление! :) – LuckyLuc