Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
... 
like image 680
HippoMan Avatar asked Jan 18 '16 18:01

HippoMan


2 Answers

IPython will do this for you automatically.

In [5]: >>> print("hello")
hello

In [10]: >>> print(
   ....: ... "hello"
   ....: )
hello
like image 92
Daniel Roseman Avatar answered Nov 15 '22 16:11

Daniel Roseman


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
   ....: 
like image 32
Padraic Cunningham Avatar answered Nov 15 '22 17:11

Padraic Cunningham