シェルへの貼り付けとはまったく同じではありませんが、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 スクリプトのフラグメントを貼り付けるスクリプトです。例をコピーし、このスクリプトを実行してから、シェルに貼り付けます。
#!/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 ('>>> ', '... ')))