Monday, November 9, 2015

"Fixing" the Python Interactive Shell Prompts

I like the concept of interactive shells for quickly testing new code.  The only issue I've had with the Python shell is the prompt (the >>> and ...) is a complete nuisance if you want to copy code out of the shell after testing it.  I can't even copy and paste something back into the same shell.  :-)

Also I think it would make more sense -- if there was any prompt at all -- that # should be added to the standard output and print statements.  That way, if the code was copied into a program, the testing output would just be ignored as comments.  (In some cases it could actually be useful as a comment, if it gives an example of data structure or function output)

So, I added a quick config file to "fix" the prompt noise.

Create a file such as ~/

And add this to the file:

import sys

# this is a patch so you can directly copy to/from the shell
# just remember to add a new line after a def as usual.

# clear those puppies!
sys.ps1 = ""
sys.ps2 = ""

# add a logger that prints output as a comment.
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
    def write(self, s):
        if s == '\n': # compress
        lines = s.split("\n")
        for line in lines:
            if len(line) > 0:
                self.terminal.write("# "+line+"\n")
        #self.terminal.write("\n") # optional space
    def flush(self):

sys.stdout = Logger()

Then  run this before starting the `python` interactive shell (or drop it in your ~/.profile)
When you start python shell, the prompts are gone. Then you will have an interactive terminal you can copy code directly from (and to itself):

Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information
def just_a_test(s):
        print s 
# works

No comments: