python: ignoring leading “>>>” and “…” in interactive mode?

天大地大妈咪最大 提交于 2019-12-09 15:46:55

问题


Many online python examples show interactive python sessions with normal leading ">>>" and "..." characters before each line.

Often, there's no way to copy this code without also getting these prefixes.

In these cases, if I want to re-paste this code into my own python interpreter after copying, I have to do some work to first strip off those prefixes.

Does anyone know of a way to get python or iPython (or any other python interpreter) to automatically ignore leading ">>>" and "..." characters on lines that are pasted in?

Example:

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

回答1:


You just need to either switch off autoindent to include >>> and ... in a multiline paste:

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

Or don't copy the >>> and it will work fine:

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

In [20]:  for i in range(10):
   ....: ...     pass
   ....: 



回答2:


IPython will do this for you automatically.

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

In [10]: >>> print(
   ....: ... "hello"
   ....: )
hello



回答3:


Not quite the same as pasting into the shell, but the doctest module can be useful. It scans a python module or regular text file looking for interactive script fragments and then runs them. Its primary use case is to blend documentation and unit test. Suppose you have a tutorial such as

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")
... 

Save it to a file and then run 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 runs the script fragments and compares it to the expected output.

UPDATE

Here's a script that will take what's in the clipboard and paste back the python script fragments. Copy your example, run this script and then paste into the 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 ('>>> ', '... ')))


来源:https://stackoverflow.com/questions/34861234/python-ignoring-leading-and-in-interactive-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!