Created
September 23, 2011 14:25
-
-
Save Djexus/1237473 to your computer and use it in GitHub Desktop.
A simple script which lets you write in the shell between two strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In memoria della programmazione funzionale, che qui giace | |
import sys | |
import tty | |
import termios | |
def write(string): | |
''' | |
Given a string, this function writes it as is on the | |
stdout | |
Usage: | |
>>> write('Hello!\n') | |
''' | |
sys.stdout.write(string) | |
sys.stdout.flush() | |
def backspace(characters): | |
''' | |
This function removes the last [characters] characters | |
from the stdout | |
Usage: | |
>>> backspace(8) | |
''' | |
sys.stdout.write('\b \b' * characters) | |
sys.stdout.flush() | |
def getchar(): | |
''' | |
This function returns the next character from the stdin | |
It works only on UNIX-like systems | |
Usage: | |
>>> char = getchar() | |
''' | |
old_settings = termios.tcgetattr(sys.stdin.fileno()) | |
tty.setraw(sys.stdin.fileno()) | |
char = sys.stdin.read(1) | |
termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old_settings) | |
return char | |
def getstring(prompt = '%s'): | |
''' | |
Given a prompt with the form '[pre] %s [post]', this | |
function lets you write between [pre] and [post] and | |
returns the last line from the stdin | |
Usage: | |
>>> string = getstring('Type between this %s and this') | |
''' | |
result = '' | |
while (not result.endswith('\r')): | |
write(prompt % result) | |
result += getchar() | |
backspace(len(prompt % result)) | |
result = result[:-2] if result[-1] == '\x7f' else result | |
write('%s\n' % (prompt % result[:-1])) | |
return result[:-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment