Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying and pasting code into the Python interpreter

Tags:

python

There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace it is not straightforward to copy and paste it a way that makes sense. (I think the whitespace gets mangled) Is there a better way? Maybe I can load the snippet from a file.

This is just an small example but if there is a lot of code I would like to avoid typing everything from the definition of the function or copy and pasting line by line.

class bcolors:      HEADER = '\033[95m'      OKBLUE = '\033[94m'      OKGREEN = '\033[92m'      WARNING = '\033[93m'      FAIL = '\033[91m'      ENDC = '\033[0m'       def disable(self):           self.HEADER = '' # I think stuff gets mangled because of the extra level of indentation          self.OKBLUE = ''          self.OKGREEN = ''          self.WARNING = ''          self.FAIL = ''          self.ENDC = '' 
like image 769
wp123 Avatar asked Mar 23 '10 15:03

wp123


People also ask

How do you paste code into python interpreter?

To copy text, just select it and hit Ctrl-C (Command-C on a Mac). If the highlight marking the selection disappears, that's normal and it means it's worked. To paste, use Ctrl-V (Command-V on a Mac).

Can you copy and paste code in python?

To copy text to the clipboard, pass a string to pyperclip. copy() . To paste the text from the clipboard, call pyperclip. paste() and the text will be returned as a string value.


1 Answers

You can usually easily and safely do copy-pasting with IPython, through the commands %cpaste (manually end code with --) and %paste (execute code immediately). This is very handy for testing code that you copy from web pages, for instance, or from your editor: these commands even strip leading prompts (like In[1] and ...) for you.

IPython also has a %run command that runs a program and leaves you in a Python shell with all the variables that were defined in the program, so that you can play with them.

In order to get help on these functions: %cpaste?, etc.

like image 130
Eric O Lebigot Avatar answered Sep 18 '22 03:09

Eric O Lebigot