[英]python: ignoring leading “>>>” and “…” in interactive mode?
许多在线python示例显示了在每行之前具有正常前导“>>>”和“...”字符的交互式python会话。
通常,如果不获取这些前缀,则无法复制此代码。
在这些情况下,如果我想在复制后将此代码重新粘贴到我自己的python解释器中,我必须做一些工作来首先剥离这些前缀。
有没有人知道如何让python或iPython(或任何其他python解释器)自动忽略粘贴的行上的前导“>>>”和“...”字符?
例:
>>> if True:
... print("x")
...
IPython会自动为您完成此操作。
In [5]: >>> print("hello")
hello
In [10]: >>> print(
....: ... "hello"
....: )
hello
您只需关闭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
....:
与粘贴到shell中的不完全相同,但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
运行脚本片段并将其与预期输出进行比较。
UPDATE
这是一个脚本,它将获取剪贴板中的内容并粘贴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 ('>>> ', '... ')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.