Example #1
0
def listen_input(screen: Screen):
    # Use custom read input function
    while True:
        # Draw the screen
        screen.update()

        c = getchar()

        try:
            if screen.updater.stop_watching_if_it_is():
                print('[ Switching, please wait... ]')
            elif c == ETX:
                break
            elif c == ESC:
                if getchar() == CSI:
                    x = getchar()
                    if x == 'A':  # UP
                        screen.on_up()
                    elif x == 'B':  # DOWN
                        screen.on_down()
                    elif x == 'D':  # LEFT
                        screen.on_left()
                    elif x == 'C':  # RIGHT
                        screen.on_right()
                    else:
                        print('Debug Warning. Undefined CSI: ', x)
            elif c == 'q':
                break
            elif c == 'h':
                print(GENERAL_HELP)
                read_input('Press Enter to continue.')
            elif screen.tab_index == 0:
                on_key_in_tab_threads(screen, c)
            elif screen.tab_index == 1:
                on_key_in_tab_projects(screen, c)
            elif screen.tab_index == 2:
                on_key_in_tab_scripts(screen, c)
            elif screen.tab_index == 3:
                pass  # TODO.
                # on_key_in_tab_config(screen, c)
            else:
                raise UndefinedBehaviorException

        except Exception as e:
            screen.log(str(e))
            if DEV:
                screen.log(traceback.format_exc())

    # Exiting...
    screen.delete_everything()
    screen.stop_and_join()
    sys.exit(0)
Example #2
0
 def loop(self):
     self.m.loop()
     c = getchar()
     if c:
         self.handler(c)
     if time.time() > self.statusTimeout:
         self.machineStatus()
         self.statusTimeout = time.time() + self.config['statusInterval']
     if time.time() > self.pmTimeout:
         self.partsStatus()
         self.pmTimeout = time.time() + self.config['pmInterval']
Example #3
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 = ''
Example #4
0
def exit():
    """Exits the program
    """
    sys.exit(0)


if __name__ == "__main__":
    print "Welcome to mypython!"
    sys.stdout.write("in [{}]: ".format(call))
    string = ""

    while True:
        #captures and handles every character
        while True:
            char = getchar()

            #handles case of ctrl-d
            if char == "\x04":
                string = ctrld(string)
                sys.stdout.write("in [{}]: ".format(call))
                break

            #handles input of up and down arrows
            if char == "\x1b":
                string = updown(sys.stdin.read(2), string)
                break

            sys.stdout.write(char)

            if char in "\r\n":
Example #5
0
    pvilast = 0.0
    count = 0
    while True:  # loop until value stops changing
        pvv = voltmeter.read()
        pvi = ammeter.read()

        if abs(pvilast - pvi) < 0.01:
            count += 1
        if count > 2:
            print
            break
        pvilast = pvi
        time.sleep(0.25)
        sys.stdout.write(".")
        sys.stdout.flush()
        c = getchar()
        if c:
            if c == "q":
                sys.exit(0)
                break

    data = urllib2.urlopen('http://192.168.0.128/data').read()
    data = json.loads(data)
    row = "%s,%d,%.6f,%d,%.6f" % (time.strftime(
        "%y%m%d-%H%M%S", time.localtime(time.time())), data['adc.pv.voltage'],
                                  pvv, data['adc.pv.current'], pvi)
    print row
    fdata.write(row + "\n")

    os.system('mpg123 -q ~/r/c/cellphone/ringtones/snare.mp3 & 2>&1')
Example #6
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 
Example #7
0
def prompt():
    """ Asks for user input using getchar(). If enter is pressed 
    the function calls the feedline()-function with the user input. 
    If arrow up/down are used the function retrieves history information. 
    The program terminates if ctrl+d is pressed in an empty-line.

    """
    global counter
    global length

    typing = True
    line = ""
    cn = length-1

    # TODO handling ctrl+d and arrow keys could possible be
    # moved to their own functions for better readability.
    while typing:
        char = getchar()
        sys.stdout.write(char)

        # Handles CTRL+D to exit.
        if char in "\x04":
            if not line == "":
                sys.stdout.write("\nKeyboardInterupt")
                line = ""
                sys.stdout.write(feedline(line))
                typing = False              
            else: 
                print"\nKthankxbye!"
                exit(0)
        
        # Handles arrows keys and command history
        # Iterates over a history list (hist_list) with a counter (cn)
        if char in "\x1b":
            key = sys.stdin.read(2)
            sys.stdout.write("\r" + " "*(len(line)+20) + "\r" + "in [%d]: "%counter)
            # Checks if arrow up or arrow down is pressed
            if key == "[A" and len(hist_list)>0:
                line = hist_list[cn]
                sys.stdout.write(line)		
                cn -= 1
                if cn == -1: cn = length-1                
            elif key == "[B" and len(hist_list)>0:
                cn += 1
                if cn == length: cn = 0                
                line = hist_list[cn]
                sys.stdout.write(line)                    
            continue

        # Stop cycle if newline
        if char in "\r\n":

            hist_list.append(line) # save input in list
            length += 1          
            # Check for magic commands
            if is_magic(line) == True:
                output = feedline("")
                sys.stdout.write(output) #To print new promt
                out_list.append(output)
            else:
                output = feedline(line)
                sys.stdout.write(output)    
                out_list.append(output)              
            output = ""
            counter += 1
            return

        # Else, simply add char to line.
        else:   
           line += char
Example #8
0
    pvilast = 0.0
    count = 0
    while True: # loop until value stops changing
        pvv = voltmeter.read()
        pvi = ammeter.read()

        if abs(pvilast - pvi) < 0.01:
            count += 1
        if count > 2:
            print 
            break
        pvilast = pvi
        time.sleep(0.25)
        sys.stdout.write(".")
        sys.stdout.flush()
        c = getchar()
        if c:
            if c == "q":
                sys.exit(0)
                break

    data = urllib2.urlopen('http://192.168.0.128/data').read()
    data = json.loads(data)
    row = "%s,%d,%.6f,%d,%.6f"%(time.strftime("%y%m%d-%H%M%S",time.localtime(time.time())),data['adc.pv.voltage'],pvv,data['adc.pv.current'],pvi)
    print row
    fdata.write(row+"\n")

    os.system('mpg123 -q ~/r/c/cellphone/ringtones/snare.mp3 & 2>&1')

    time.sleep(0.5)
    pvilast = ammeter.read()
Example #9
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
Example #10
0
def prompt():
    """ Asks for user input using getchar(). If enter is pressed 
    the function calls the feedline()-function with the user input. 
    If arrow up/down are used the function retrieves history information. 
    The program terminates if ctrl+d is pressed in an empty-line.

    """
    global counter
    global length

    typing = True
    line = ""
    cn = length - 1

    # TODO handling ctrl+d and arrow keys could possible be
    # moved to their own functions for better readability.
    while typing:
        char = getchar()
        sys.stdout.write(char)

        # Handles CTRL+D to exit.
        if char in "\x04":
            if not line == "":
                sys.stdout.write("\nKeyboardInterupt")
                line = ""
                sys.stdout.write(feedline(line))
                typing = False
            else:
                print "\nKthankxbye!"
                exit(0)

        # Handles arrows keys and command history
        # Iterates over a history list (hist_list) with a counter (cn)
        if char in "\x1b":
            key = sys.stdin.read(2)
            sys.stdout.write("\r" + " " * (len(line) + 20) + "\r" +
                             "in [%d]: " % counter)
            # Checks if arrow up or arrow down is pressed
            if key == "[A" and len(hist_list) > 0:
                line = hist_list[cn]
                sys.stdout.write(line)
                cn -= 1
                if cn == -1: cn = length - 1
            elif key == "[B" and len(hist_list) > 0:
                cn += 1
                if cn == length: cn = 0
                line = hist_list[cn]
                sys.stdout.write(line)
            continue

        # Stop cycle if newline
        if char in "\r\n":

            hist_list.append(line)  # save input in list
            length += 1
            # Check for magic commands
            if is_magic(line) == True:
                output = feedline("")
                sys.stdout.write(output)  #To print new promt
                out_list.append(output)
            else:
                output = feedline(line)
                sys.stdout.write(output)
                out_list.append(output)
            output = ""
            counter += 1
            return

        # Else, simply add char to line.
        else:
            line += char