python:在交互模式下忽略前导">>>"和"..."?

Hip*_*Man 9 python interpreter ipython pasting

许多在线python示例显示了在每行之前具有正常前导">>>"和"..."字符的交互式python会话.

通常,如果不获取这些前缀,则无法复制此代码.

在这些情况下,如果我想在复制后将此代码重新粘贴到我自己的python解释器中,我必须做一些工作来首先剥离这些前缀.

有没有人知道如何让python或iPython(或任何其他python解释器)自动忽略粘贴的行上的前导">>>"和"..."字符?

例:

>>> if True:
...     print("x")
... 
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 5

IPython会自动为您完成此操作.

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

In [10]: >>> print(
   ....: ... "hello"
   ....: )
hello
Run Code Online (Sandbox Code Playgroud)


Pad*_*ham 3

您只需要关闭 autoindent以在多行粘贴中包含>>>和:...

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
Run Code Online (Sandbox Code Playgroud)

或者不要复制它>>>,它会正常工作:

In [20]: %autoindent
Automatic indentation is: OFF

In [20]:  for i in range(10):
   ....: ...     pass
   ....: 
Run Code Online (Sandbox Code Playgroud)