50

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 = ''
Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
wp123
  • 987
  • 5
  • 13
  • 18

11 Answers11

27

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.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
20

You can simply convert all tabs to spaces and remove ALL empty lines. So you will be able to paste any code to python console (e.g.: python2.6)

0script0
  • 471
  • 5
  • 11
16

You can call execfile(filename). More or less the same as importing a module, except that it skips the module administration part and doesn't require you to add a folder to sys.path.

EDIT: To address the original question: copy-pasted code can be executed by calling exec(codestring).

Pieter Witvoet
  • 2,773
  • 1
  • 22
  • 33
  • 18
    how does this answer the question "how do I paste python code?" – Bryan Oakley Mar 23 '10 at 21:36
  • 1
    You are correct that it does not really, but I prefer this solution because it doesn't require you to pick a specific shell or use a specific IDE. The other solutions are also excellent but I accepted the one that is most general. – wp123 Mar 24 '10 at 04:21
  • @Bryan Oakley: You're right, execfile(filename) can't be used for that. exec(codestring) can, though. – Pieter Witvoet Mar 25 '10 at 08:17
  • 3
    To keep this answer current, note that `execfile` was removed from python 3. See https://stackoverflow.com/q/436198/353278 – Jeff Jul 03 '17 at 17:56
7

My answer is specifically about copy-pasting into the standard python shell (only tested on linux).

Depending on where the code comes from and how it is originally formatted the whitespace may or may not matter. In particular about your example snippet - copy-pasted from SO's code-formatted section - it doesn't matter (assuming the code is properly indented to be executable).

The empty line, however, does cause trouble in the standard python interpreter because it normally is the shell-s de-indent cmd. In your snippet's case the empty line preceeding the disable() function definition ends/exits the class definition prematurely, so when the disable() definition line comes in an indentation error is detected:

>>> class bcolors: 
...     HEADER = '\033[95m' 
...     OKBLUE = '\033[94m' 
...     OKGREEN = '\033[92m' 
...     WARNING = '\033[93m' 
...     FAIL = '\033[91m' 
...     ENDC = '\033[0m' 
... 
>>> def disable(self):  
  File "<stdin>", line 1
    def disable(self):  
    ^
IndentationError: unexpected indent
>>> 

So you just need to pay attention at those empty lines. Your snippet needs just 2 multi-line copy-paste ops to work around that empty line.

The only other thing I needed - for copy-pasting just sections of already indented code (say functions from inside classes) - one extra level of indentation to not need to re-do the indentation of the copied code. For that a leading if 1: line prior to pasting the snippet and an Enter (i.e. empty line) after do the trick:

>>> if 1:
...     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 = ''
... 
>>>
Dan Cornilescu
  • 39,470
  • 12
  • 57
  • 97
  • 2
    An alternative to using two copy-paste ops is to simply make sure the "blank" line is indented the same amount as the rest of your code. And to avoid using `if 1:` there are a few alternatives: if your editor has a visual-block selection (rather than line-selection), use that. Or, select the lines you want to copy and un-indent them prior to copying them. – Jeff Jul 03 '17 at 18:03
6

You can just import the file into the python interpreter. This will load the class in, and allow you to run the code.

For instance, create a file named "bgcolors.py" and copy and paste your code inside. Then using the python interpreter, you just type "import bgcolors" and you should be able to run it.

You can read more here:

http://docs.python.org/tutorial/modules.html

Anton
  • 1,387
  • 2
  • 17
  • 30
  • A second `import bgcolors` in the same session will do nothing because import "knows" bgcolors has already been imported. – msw Mar 23 '10 at 15:49
  • 1
    Rather than importing it explicitly in the shell, call python like so: `python -m bgcolors.py` and you will be presented with an environment where that module is already loaded. – vezult Mar 23 '10 at 15:49
  • I think the -m option only works for file in sys.path. But my script is not in the standard library. – wp123 Mar 23 '10 at 16:03
  • @wpeters: It works just like any import. If your module is not in the current directory, in any bourne compatible shell, you can invoke python like so: `PYTHONPATH=/path/to/module/dir python -m bgcolors.py` , or by any other means, set the PYTHONPATH environment variable. – vezult Mar 25 '10 at 02:07
5

You can use IPython which is much better python repl. It has command for getting input from external editor by using %edit command.

Łukasz
  • 35,061
  • 4
  • 33
  • 33
3

Dreampie allows you to copy and paste code with proper indentation.

Ashley
  • 2,256
  • 1
  • 33
  • 62
2

The IDLE interface does go to effort to preserve the proper indentation of pasted text.

msw
  • 42,753
  • 9
  • 87
  • 112
0

I had this problem recently and ultimately just needed to change my editor's indentation setting from tabs to spaces. (I was running the interpreter using the OSX Terminal.) Once I did this, copy & paste worked fine.

dwat
  • 312
  • 2
  • 6
  • 14
0

There is an inbuilt method call "indent region & dedent region" and you can just use it. After you paste a lot of code at once you can select them all and adjust the whitespace.

Datong
  • 9
  • 1
-4

For those having issues copy/pasting using ctrl-c & ctrl-v in the python interpreter shell on Windows where it simply shows:

>>> ^V

simply right-mouse-click the application window title bar and select default or properties, then you want to un-check Use legacy console (requires relaunch) ensuring that now Enable Ctrl key shortcuts is checked, then close and re-open the Python interpreter console window.

Maj. Dave
  • 93
  • 1
  • 2