#!/usr/bin/python # Python paste utility by Keith Buck # Copyright (C) 2012. # Distributed under the MIT license. # I had no idea this would be this complicated when I originally wrote it. I feel dirty. import os import sys import random import string def randfilename(suffix=".txt", length=10, alphabet=(string.ascii_letters + string.digits)): randstr = ''.join(random.choice(alphabet) for x in range(length)) return randstr + suffix def paste(dest, source=sys.stdin, timeout=1, raw=True): if raw and source.isatty(): import sys, tty, termios termfd = source.fileno() old_config = None try: old_config = termios.tcgetattr(termfd) tty.setcbreak(termfd) #tty.setraw(termfd) # Warning: this disables translation of line endings. paste_helper(dest, source, timeout) finally: termios.tcsetattr(termfd, termios.TCSADRAIN, old_config) else: paste_helper(dest, source, timeout) def paste_helper(dest, source, timeout): import select, fcntl fd = None old_flags = None try: fd = source.fileno() old_flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK) t = None # Don't timeout for the first iteration. while True: if (select.select([source], [], [], t) != ([source], [], [])): # Quit if we've timed out. break t = timeout text = source.read() if not text: # Quit if we get an EOF. break dest.write(text) sys.stderr.write(".") # For debugging. #for char in text: #sys.stdout.write(str(ord(char)) + " ") finally: fcntl.fcntl(fd, fcntl.F_SETFL, old_flags) sys.stderr.write("\n") if __name__ == "__main__": # Configuration default_dir = os.path.expanduser("~/public_html/private/paste") url = "http://anacreon.mrflea.net/~kbuck/private/paste/" timeout = 0.5 # End configuration. __doc__ = """usage: %s [filename] Pastes all input from the console to [filename], or to a randomly-named file in %s if filename is not specified. """ % (sys.argv[0], default_dir) defaulted = False path = None filename = None if len(sys.argv) > 1: if sys.argv[1] == "--help" or sys.argv[1] == "-h" or len(sys.argv) > 2: print __doc__ sys.exit(-1) path = sys.argv[1] if not path: path = default_dir defaulted = True if os.path.isdir(path): filename = randfilename() path = os.path.join(path, filename) if (os.path.exists(path)): print "File %s already exists, exiting..." % path sys.exit(-2) try: f = open(path, 'w') except IOError, e: print "Couldn't open %s: %s" % (path, os.strerror(e.errno)) sys.exit(-3) paste(f) f.close() print "Paste complete: %s" % path if defaulted: print "URL: %s" % (url + filename)