示例#1
0
def shellInterpreter():
    assert request.method == 'POST'
    pythonCommand = request.form["pythonCommand"]    
    try:
        terminal=request.form["terminal"]
        terminal+=pythonCommand+"\r\n"+feedline(pythonCommand,namespace)
    except:
        terminal="In [0]: "+pythonCommand+"\r\n"+feedline(pythonCommand,namespace)
    return render_template('shell.html',result=terminal)
示例#2
0
def prompt():
	history = []
	print "Welcome to mypython!"
	buffr = ""
	hist_pos = 0
	stdout.write(feedline('')) # to write the first line

	while True:
		usr_input = getchar()

		if usr_input == '\x1b':
			if history != []:
				arrow_dir = stdin.read(2)
				if arrow_dir == '[C' or arrow_dir == '[D':
					continue
				else:
					stdout.write('\n' + feedline('\n'))
					hist_pos = setHistPos(arrow_dir, hist_pos, history)
					buffr = history[hist_pos]
					stdout.write(buffr)
			continue
					

		stdout.write(usr_input)
		buffr += usr_input # add to buffer if not arrows
		
		if usr_input == '\x04':
			if buffr == '\x04':
				stdout.write('\nkthanksbye!\n')
				break

			else:
				buffr = ''
				stdout.write('\nKeyboardinterupt')
				stdout.write('\n' + feedline(buffr))
				continue

		if usr_input == '\r' or usr_input == '\n':
			
			stdout.write('\n' + feedline(buffr))
			
			if buffr.startswith('%save'):
				buffr = buffr.split(' ', 1)[1]
				text_file = open(buffr + '.txt', 'w')
				text_file.write('History:\n')
				for element in history:
					text_file.write(element + '\n')
				text_file.close()

			if buffr.strip() != '':
				history.append(buffr)
			buffr = ''
示例#3
0
def prompt():
    global retValue
    command = request.form['command']
    retValue += feedline(command)
    #retValue = retValue.replace("\n", "<br />")

    return render_template('prompt.html', input=retValue)
示例#4
0
def handle_feedline():
    assert request.method == 'POST'

    string = request.form["string"]

    history.append(string+": "+feedline(string))
    return render_template('mypython.html', feedback=history)
示例#5
0
def my_form_post():
    """
    Returns (creates) html of flask webapp when user has input some
    string to be validated by feedline(). Also, displays earlier input
    and output.
    """
    all_output = feedline(request.form['text'], True)
    all_output = re.sub('\n', '<br>', all_output)  # Change \n to <br>
    html = """
    <html>
       <head>
           <title>MyPython WebApp</title>
       </head>
       <body>
           <div id="container">
               <div class="title">
                   <h1>MyPython WebApp</h1>
               </div>
          </div>
          <p>%s
          </p>
          <div id="content">
            <form action="." method="POST">
              <input type="text" name="text">
              <input type="submit" name="my-form" value="Send">
            </form>
            </div>
       </body>
    </html>""" % (all_output)
    return html
示例#6
0
def my_form_post():
    """
    Returns (creates) html of flask webapp when user has input some
    string to be validated by feedline(). Also, displays earlier input
    and output.
    """
    all_output = feedline(request.form['text'],True)
    all_output = re.sub('\n','<br>',all_output) # Change \n to <br>
    html = """
    <html>
       <head>
           <title>MyPython WebApp</title>
       </head>
       <body>
           <div id="container">
               <div class="title">
                   <h1>MyPython WebApp</h1>
               </div>
          </div>
          <p>%s
          </p>
          <div id="content">
            <form action="." method="POST">
              <input type="text" name="text">
              <input type="submit" name="my-form" value="Send">
            </form>
            </div>
       </body>
    </html>""" %(all_output)
    return html
示例#7
0
def ctrld(string):
    """Handle Ctrl+D input.

    Args:
        string (str): input, if any, already written into terminal.
    Returns:
        empty string

    Example usage:
    >>> print ctrld("any string")
    ""
    """
    if string:
        print "\nKeyboardusInterruptus"
        #reset history-position in case the input is from history
        position = len(history)
        #make an empty call to reset input-prompt
        sys.stdout.write(feedline(""))
        return ""
    else:
        print "\nkthxbye"
        exit()
示例#8
0
                #Empty cache in case history was involved
                cache = ""

                if string:
                    #magic commands passed to os
                    if string[0] == "!":
                        string = magic_sys(string)
                    #magic command to display docstring of object
                    elif string[-1] == "?":
                        string = magic_inspect(string)
                    #magic command to save all input lines for one interactive session
                    elif string[0:5] == "%save":
                        string = magic_save(string)
                    else:
                        result = feedline(string)
                        if result:
                            sys.stdout.write("out [{}]: ".format(call) +
                                             result)

                    call += 1

                #append to history
                if string and string not in history:
                    history.append(string)
                #update position for new length of history
                position = len(history)

                #empty buffer
                string = ""
示例#9
0
from flask import Flask
from flask import render_template
from flask import request
from feedline import feedline

retValue = feedline('')
APP = Flask(__name__)


@APP.route('/')
def index():
    return render_template('prompt.html')


@APP.route('/prompt', methods=['POST'])
def prompt():
    global retValue
    command = request.form['command']
    retValue += feedline(command)
    #retValue = retValue.replace("\n", "<br />")

    return render_template('prompt.html', input=retValue)


if __name__ == "__main__":
    APP.run(debug=True)
示例#10
0
                if code:      #Empty the buffer
                    sys.stdout.write("\r\nKeyboardInterupt\n")
                    sys.stdout.write("In [{0}]: ".format(lineNumber-1))
                    lineNumber-=1#Program should not increase the prompt line number
                    break
                else:         #Exit from the program
                    sys.stdout.write("\nThanks! \n")
                    sys.exit(0)                
            # stop cycle
            if char in "\r\n":
                #If user press the enter (based on the OS)
                if code=="":#program should not increase the number line when we enter empty command
                    lineNumber-=1
                    sys.stdout.write("\r\nIn [{0}]: ".format(lineNumber))
                    break                
                if not line:
                    sys.stdout.write("\n")
                    commandHistory.append(code)
                    commandHistoryPointer=len(commandHistory)-1
                    commandHistoryPointer+=1
                    sys.stdout.write(feedline(code,localNamespace))
                else:
                    sys.stdout.write("\n")
                    commandHistory.append(code)
                    commandHistoryPointer=len(commandHistory)-1
                    commandHistoryPointer+=1
                    sys.stdout.write(feedline(code,localNamespace))
                break;                    
            # add char to line
            line+=char
示例#11
0
def prompt():
    """
    Prompt function for initializing the shell.
    Let's you navigate the string, adds some color to the output.
    It remebers previous given commands. Possible to save the session to file by doing %save filename
    
    When navigating the history, it prints it in a new line everytime. This can easily be changed
    by clearing the sys.stdin and writing it again. The example in the assigment did it my way, so I stuck
    by it. 
    
    cur_pos is the current position. 
    tmpcount is the counter for navigating the history. 
    cmd_count is the command count. 
    Colors are self explanatory. 
    ! Will execute a sh command. 
    ? Will execute a help command
    % Will save the the buffer parameter to a given file.
    

    """
    input=""            # Buffer for line
    tmpcount=-1         # Counter for history. Default is -1 for simplicity. 
    RED='\x1b[31;1m'    # Red for error
    RED2='\x1b[91m'     # Red for error message
    GREEN='\x1b[92;1m'  # 'In []'
    BLUE='\x1b[94;1m'   # Blue for 'Out []'
    MAGENTA='\x1b[95;1m'# Magenta for navigation history. 
    RESET= '\x1b[0m'    # RESET to default
    ARROW='\x1b'        # First byte of an arrow key  
    cmd_count=0;        # Number of commands
    history=list()      # The command history
    cur_pos=0           # Current position in the line. 
    print "Welcome to mypython.py:"
    print "!sh-command  Will execute a sh command. \n?object      Will execute a help command\n%save x      Will save the the buffer parameter to a given file(x)."
    sys.stdout.write("{0}In [{1}]{2} ".format(GREEN,cmd_count,RESET))
    while(True):

        Arrow=True                  # assume it's an arrow, by default
        char=getchar()              # get a character from stdin. 
        if char==ARROW:             # arrow key was pressed. 
            char+=sys.stdin.read(2) # read the next 2 bytes.
            if char=='\x1b[A':      # up arrow was pressed.
                cur_pos=0
                if tmpcount==0:     # already on the first command. fifo-list(stack)
                    continue

                if cmd_count>0:     # not on the first command
                    tmpcount= (cmd_count-1) if tmpcount==-1  else (tmpcount-1 if tmpcount>0 else 0)
                    sys.stdout.write("\n{0}In [{1}] {2}{3} {4}".format(GREEN,cmd_count,MAGENTA,history[tmpcount],RESET))
                    input=history[tmpcount]
                
            elif char=='\x1b[B':    # the down arrow was pressed
                cur_pos=0
                if not tmpcount==-1 and tmpcount<(cmd_count-1): # makes sure we're in the history somewhere
                    tmpcount=tmpcount+1
                    sys.stdout.write("\n{0}In [{1}] {2}{3} {4}".format(GREEN,cmd_count,MAGENTA,history[tmpcount],RESET))
                    input=history[tmpcount]

                elif tmpcount==(cmd_count-1): #we're at the last command. same as ctrl+d
                    sys.stdout.write("\r{0}In [{1}]{2} \033[K".format(GREEN,cmd_count,RESET))
                    input=""
                else:                    # not in the history
                    continue

            elif char=='\x1b[C':         # right arrow was pressed
                if cur_pos>0:
                    sys.stdout.write("\033[C")
                    cur_pos-=1
                continue

            elif char=='\x1b[D':         # left arrow was pressed
                if cur_pos<len(input):
                    cur_pos+=1
                    sys.stdout.write("\033[D")
                continue
        else:
            if hex(ord(char))=='0x4':    # ctrl+D
                if not input:            # nothing in the line, exit
                    print "{0}exiting..".format(RESET)
                    sys.exit(0) 

                else:                    # something in the line, clear it. 
                    input=""
                    sys.stdout.write("\r{0}In [{1}]{2} \033[K".format(GREEN,cmd_count,RESET))

            elif hex(ord(char))=='0x7f': # backspace
                if cur_pos==0:
                    input=input[:-1]
                    sys.stdout.write("\r{0}In [{1}]{2} {3}\033[K".format(GREEN,cmd_count,RESET,input))

                else:
                    input=input[:-cur_pos-1]+input[-cur_pos:]        # remove one char
                    sys.stdout.write("\r{0}In [{1}]{2} {3}\033[K".format(GREEN,cmd_count,RESET,input))
                    sys.stdout.write('\033[D'*cur_pos) #setting the cursor back

            else:                                      # just a char
                if char:
                    if cur_pos==0:                     # the end of the line
                        tmpcount=-1                    # reset tmpcount
                        sys.stdout.write(char)         # print char to screen
                        Arrow=False                    # an arrow was not pressed
                    else:                              # not at the end of the line
                        input=input[:-cur_pos]+char+input[-cur_pos:] 
                        sys.stdout.write("\r{0}In [{1}]{2} {3}\033[K".format(GREEN,cmd_count,RESET,input))
                        sys.stdout.write('\033[D'*cur_pos) # setting the cursor back to where it was

        if char in "\r\n": # enter was pressed
            cur_pos=0      # reset posision

            if not input:  # line was empty, print out standard message without counting
                sys.stdout.write("\n{0}In [{1}]{2} ".format(GREEN,cmd_count,RESET))
                continue
            else:          # line was not empty


                if 'exit' in input or 'quit' in input:
                    sys.stdout.write("\n\033[K".format(GREEN,cmd_count,RESET))
                    print "{0}exiting...".format(RESET)
                    sys.exit(0)

                history.append(input) 


                if input[0]=='!' or input[0]=='?' or input[0]=='%': # one of the "special" commands
                    out=feedline(input,namespace,history)
                else:
                    out=feedline(input,namespace) 


                if 'Error' in out:         # some kind of error message
                    sys.stdout.write("\n{0}Out[{1}]{2} {3}{4}{5}\n".format(RED,cmd_count,RESET,RED2,out,RESET))    
                elif out:                  # not an error
                    sys.stdout.write("\n{0}Out[{1}] {2}{3}".format(BLUE,cmd_count,RESET,out))
                else:                      # no output 
                    sys.stdout.write("\n")

                cmd_count+=1                                        # count commands
                sys.stdout.write("{0}In [{1}] {2}".format(GREEN,cmd_count,RESET))

                input=""
                continue

        if not Arrow:    # if not an arrow key add to line
            input += char 
示例#12
0
def prompt():
    """
    IPython clone with all the basic python shell possibilites.

    Args:
        None
    Returns:
        Nothing

    Example usage
    >>> python mypython.py
    Welcome to mypython!
    in [0]:from math import cos, pi
    in [1]:x = pi/2.0
    in [2]:cos(x**2)
    out[3]:-0.78121189211
    """
    sys.stdout.write("Welcome to mypython!\nin [0]:")
    sys.stdout.write("")
    line = ""
    cmd_history = []  #List of all used commands
    save_line_on_first_arrow_key = True
    up_counter = 0 # Will be index of cmd_history when multplied with -1
    while True:
        arrow_key      = None
        char_to_screen = True
        char_to_line   = True
        char = getchar() # Catch user input (one character at the time)

        if char == "\x1b":
            arrow_key = sys.stdin.read(2)
        if arrow_key in ["[A", "[B"]: # Up or down
            char_to_screen = False
            char_to_line   = False
            if save_line_on_first_arrow_key:
                stored_current_line = line
                save_line_on_first_arrow_key = False
        if arrow_key == "[A": # UP is pressed
            up_counter += 1 if len(cmd_history) > up_counter else 0
            if not cmd_history:
                # Basicly do nothing, nothing to grab
                pass
            else:
                if up_counter == 1:
                    prev_cmd = cmd_history[-1*up_counter]
                    chars_to_remove = "\b"*len(line) + " "*len(line) + "\b"*len(line)
                    sys.stdout.write(chars_to_remove + prev_cmd)
                    line = prev_cmd
                else:
                    prev_cmd = cmd_history[-1*up_counter]
                    number   = len(prev_cmd)
                    chars_to_remove = "\b"*number + " "*number + "\b"*number
                    sys.stdout.write(chars_to_remove + prev_cmd)
                    line = prev_cmd
        if arrow_key == "[B": # DOWN is pressed
            if up_counter == 0:
                pass
            elif up_counter == 1:
                next_cmd = stored_current_line
                number   = len(cmd_history[-1*up_counter])
                chars_to_remove = "\b"*number + " "*number + "\b"*number
                sys.stdout.write(chars_to_remove + next_cmd)
                line = next_cmd
            else:
                next_cmd = cmd_history[-1*up_counter+1]
                number   = len(next_cmd)
                chars_to_remove = "\b"*number + " "*number + "\b"*number
                sys.stdout.write(chars_to_remove + next_cmd)
                line = next_cmd
            up_counter -= 1 if up_counter > 0 else 0


        if char == "\x04": # Ctrl + D = quit
            char_to_line   = False
            char_to_screen = False
            if line == "":
                sys.stdout.write("\n")
                sys.exit(0)
            else:
                sys.stdout.write("\nKeyboardInterupt\n")
                sys.stdout.write(feedline(""))
                line = ""

        if char == "\x7f": # Backspace is pressed
                if line: # not empty
                    sys.stdout.write("\b \b")
                    line = line[:-1]
                char_to_line   = False
                char_to_screen = False

        if char == "\t": # Tab is pressed
                char_to_screen = False
                char_to_line   = False
                matches = []
                line_to_match = re.split(r'[^\w\d%]+',line)[-1]
                if line_to_match:
                    for variable in namespace:
                        if variable.startswith(line_to_match):
                            matches.append(variable)
                if len(matches) == 1: # Only one match: Use it!
                    perfect_match = matches[0]
                    # Print the rest of the characters:
                    sys.stdout.write(perfect_match[len(line_to_match):])
                    line += perfect_match[len(line_to_match):]
                elif len(matches) > 1:
                    sys.stdout.write("\n")
                    for possible_match in matches:
                        sys.stdout.write(possible_match+"  ")
                    sys.stdout.write('\n' + feedline('') + line_to_match)

        if char_to_screen:
            sys.stdout.write(char) # ... and print that character to screen

        if char in "\r\n":
            # When enter is pressed (i.e. char is 'newline') send all
            # buffered input to feedline
            sys.stdout.write('\n' + feedline(line))
            if line != '': # Dont append empty commands
                cmd_history.append(line)
            # Reset variables:
            line = ""
            up_counter = 0
            save_line_on_first_arrow_key = True

        elif char_to_line:
            line += char # add char to line/buffer