簡體   English   中英

python:在交互模式下忽略前導“>>>”和“...”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM