pythonipythoninterpreterpasting

python: ignoring leading ">>>" and "..." in interactive mode?


Many online python examples show interactive python sessions with normal leading ">>>" and "..." characters before each line.

Often, there's no way to copy this code without also getting these prefixes.

In these cases, if I want to re-paste this code into my own python interpreter after copying, I have to do some work to first strip off those prefixes.

Does anyone know of a way to get python or iPython (or any other python interpreter) to automatically ignore leading ">>>" and "..." characters on lines that are pasted in?

Example:

>>> if True:
...     print("x")
... 

Solution

  • You just need to either switch off autoindent to include >>> and ... in a multiline paste:

    In [14]: %autoindent
    Automatic indentation is: OFF
    In [15]: >>> for i in range(10):
       ....: ...     pass
       ....: 
    
    In [16]: >>> for i in range(10):
       ...: ...     pass
       ...: ... 
    In [17]: >>> for i in range(10):
       ...: ...     pass
       ...: ... 
    
    In [18]: %autoindent
    Automatic indentation is: ON
    
    In [19]: >>> for i in range(10):
       ....:     ...     pass
       ....:     
      File "<ipython-input-17-5a70fbf9a5a4>", line 2
        ...     pass
        ^
    SyntaxError: invalid syntax
    

    Or don't copy the >>> and it will work fine:

    In [20]: %autoindent
    Automatic indentation is: OFF
    
    In [20]:  for i in range(10):
       ....: ...     pass
       ....: