9

许多在线 python 示例显示交互式 python 会话,每行前带有正常的前导“>>>”和“...”字符。

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

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

有谁知道让python或iPython(或任何其他python解释器)自动忽略粘贴行上的前导“>>>”和“...”字符的方法?

例子:

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

3 回答 3

5

IPython 会自动为你做这件事。

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

In [10]: >>> print(
   ....: ... "hello"
   ....: )
hello
于 2016-01-18T18:09:30.253 回答
2

您只需要关闭 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

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

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

In [20]:  for i in range(10):
   ....: ...     pass
   ....: 
于 2016-01-18T18:30:36.613 回答
1

与粘贴到外壳中并不完全相同,但该doctest模块可能很有用。它扫描 python 模块或常规文本文件以查找交互式脚本片段,然后运行它们。它的主要用例是混合文档和单元测试。假设您有一个教程,例如

This is some code to demonstrate the power of the `if`
statement. 

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

Remember, each `if` increases entropy in the universe,
so use with care.

>>> if False:
...     print("y")
... 

将其保存到文件然后运行doctest

$ python -m doctest -v k.txt
Trying:
    if True:
        print("x")
Expecting:
    x
ok
Trying:
    if False:
        print("y")
Expecting nothing
ok
1 items passed all tests:
   2 tests in k.txt
2 tests in 1 items.
2 passed and 0 failed.
Test passed.

doctest运行脚本片段并将其与预期输出进行比较。

更新

这是一个脚本,它将获取剪贴板中的内容并粘贴回 python 脚本片段。复制您的示例,运行此脚本,然后粘贴到 shell 中。

#!/usr/bin/env python3

import os
import pyperclip

pyperclip.copy(os.linesep.join(line[4:] 
    for line in pyperclip.paste().split(os.linesep)
    if line[:4] in ('>>> ', '... ')))
于 2016-01-18T18:49:31.433 回答