【问题标题】:How can I test several lines of quickly?如何快速测试几行?
【发布时间】:2016-06-20 15:49:45
【问题描述】:

假设我正在浏览 hithub,我看到了一些我想在我的笔记本电脑上运行的 python 代码。 有没有办法只复制、粘贴并运行它而无需创建文件、粘贴代码并运行它?

我尝试在终端上运行ipython,然后%cpaste,最后粘贴了代码,但还是不行。

谢谢!

更新:(更多信息)

我试图运行这个:

import scrapy

class RedditScraper(scrapy.Spider):
    keyword     =   raw_input("Enter the keyword to scrap: ")
    name        =   'redditscraper'
    oop_url     =   'https://www.reddit.com/r/'+keyword
    start_urls  =   [oop_url]

    def parse(self, response):
            for post in response.css('a.title.may-blank::text').extract():
                print post + "\n"

我得到了这个:

ariel@EscritorioPC:~$ ipython
Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
Type "copyright", "credits" or "license" for more information.

IPython 2.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:import scrapy
:
:class RedditScraper(scrapy.Spider):
:       keyword 
Display all 341 possibilities? (y or n)
%%!
%%HTML
%%SVG
%%bash
%%capture
%%debug
%%file
%%html
%%javascript
%%latex
%%perl
%%prun
%%pypy
%%python
%%python2
%%python3
%%ruby
%%script
%%sh
%%svg
%%sx
%%system
%%time
%%timeit
%%writefile
%alias
%alias_magic
%autocall
%autoindent
%automagic
%bookmark
%cat
%cd
%clear
%colors
%config
%cp
%cpaste
%debug
%dhist
%dirs
%doctest_mode
%ed
%edit
%env
%gui
%hist
%history
%install_default_config
%install_ext
%install_profiles
%killbgscripts
%ldir
%less
%lf
%lk
%ll
%load
%load_ext
%loadpy
%logoff
%logon
%logstart
%logstate
%logstop
%ls
%lsmagic
%lx
%macro
%magic
%man
%matplotlib
%mkdir
%more
%mv
%notebook
%page
%paste
%pastebin
%pdb
%pdef
%pdoc
%pfile
%pinfo
%pinfo2
%popd
%pprint
%precision
%profile
%prun
%psearch
%psource
%pushd
%pwd
%pycat
%pylab
%quickref
%recall
%rehashx
%reload_ext
%rep
%rerun
%reset
%reset_selective
%rm
%rmdir
%run
%save
%sc
%store
%sx
%system
%tb
%time
%timeit
%unalias
%unload_ext
%who
%who_ls
%whos
%xdel
%xmode
Android
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
Desktop
Documents
Downloads
EOFError
Ellipsis
EnvironmentError
Exception
False
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
In
IndentationError
IndexError
Kali-Linux-2.0.0-vm-amd64
KeyError
KeyboardInterrupt
LPCXpresso
LookupError
MemoryError
Music
NameError
None
NotImplemented
NotImplementedError
OSError
Out
OverflowError
PendingDeprecationWarning
Pictures
Programas
Public
ReferenceError
RuntimeError
RuntimeWarning
Screenshot\ from\ 2016-06-20\ 03_49_46.png
Screenshot\ from\ 2016-06-20\ 03_52_40.png
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
Templates
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Videos
VirtualBox\ VMs
Warning
ZeroDivisionError
_
__
__IPYTHON__
__IPYTHON__active
___
__builtin__
__debug__
__doc__
__import__
__name__
__package__
_dh
_i
_i1
_ih
_ii
_iii
_oh
_sh
abs
all
and
any
apply
as
assert
basestring
bin
bool
break
buffer
bytearray
bytes
callable
chr
class
classmethod
cmp
coerce
compile
complex
continue
copyright
credits
def
del
delattr
dict
dir
divmod
dreload
elif
else
enumerate
eval
examples.desktop
except
exec
execfile
exit
file
filter
finally
float
for
format
from
frozenset
get_ipython
getattr
global
globals
hasattr
hash
help
hex
id
if
import
in
input
int
intel
intern
is
isinstance
issubclass
iter
kivy-1.9.1
lambda
len
license
list
locals
logs
long
man.pdf
map
max
memoryview
min
nano.save
next
not
object
oct
open
or
ord
pass
photorec.ses
pow
primerapp
print
property
quit
raise
range
raw_input
reduce
reload
repr
return
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
titanium.studio.linux.gtk.x86_64.zip
tools
try
tuple
type
unichr
unicode
vars
wget.log
while
with
www.draidel.com
xdk_web_linux64
xrange
yield
zip
:       keyword = 
Display all 313 possibilities? (y or n)
%%!                        RuntimeWarning
%%HTML                     StandardError
%%SVG                      StopIteration
%%bash                     SyntaxError
%%capture                  SyntaxWarning
%%debug                    SystemError
%%file                     SystemExit
%%html                     TabError
%%javascript               True
%%latex                    TypeError
%%perl                     UnboundLocalError
%%prun                     UnicodeDecodeError
%%pypy                     UnicodeEncodeError
%%python                   UnicodeError
%%python2                  UnicodeTranslateError
%%python3                  UnicodeWarning
%%ruby                     UserWarning
%%script                   ValueError
%%sh                       Warning
%%svg                      ZeroDivisionError
%%sx                       _
%%system                   __
%%time                     __IPYTHON__
%%timeit                   __IPYTHON__active
%%writefile                ___
%alias                     __builtin__
%alias_magic               __debug__
%autocall                  __doc__
%autoindent                __import__
%automagic                 __name__
%bookmark                  __package__
%cat                       _dh
%cd                        _i
%clear                     _i1
%colors                    _ih
%config                    _ii
%cp                        _iii
%cpaste                    _oh
%debug                     _sh
%dhist                     abs
%dirs                      all
%doctest_mode              and
%ed                        any
%edit                      apply
%env                       as
%gui                       assert
%hist                      basestring
%history                   bin
%install_default_config    bool
%install_ext               break
%install_profiles          buffer
%killbgscripts             bytearray
%ldir                      bytes
%less                      callable
%lf                        chr
%lk                        class
%ll                        classmethod
%load                      cmp
%load_ext                  coerce
%loadpy                    compile
%logoff                    complex
%logon                     continue
%logstart                  copyright
%logstate                  credits
%logstop                   def
%ls                        del
%lsmagic                   delattr
%lx                        dict
%macro                     dir
%magic                     divmod
%man                       dreload
%matplotlib                elif
%mkdir                     else
%more                      enumerate
%mv                        eval
%notebook                  except
%page                      exec
%paste                     execfile
%pastebin                  exit
%pdb                       file
%pdef                      filter
%pdoc                      finally
%pfile                     float
%pinfo                     for
%pinfo2                    format
%popd                      from
%pprint                    frozenset
%precision                 get_ipython
%profile                   getattr
%prun                      global
%psearch                   globals
%psource                   hasattr
%pushd                     hash
%pwd                       help
%pycat                     hex
%pylab                     id
%quickref                  if
%recall                    import
%rehashx                   in
%reload_ext                input
%rep                       int
%rerun                     intern
%reset                     is
%reset_selective           isinstance
%rm                        issubclass
%rmdir                     iter
%run                       lambda
%save                      len
%sc                        license
%store                     list
%sx                        locals
%system                    long
%tb                        map
%time                      max
%timeit                    memoryview
%unalias                   min
%unload_ext                next
%who                       not
%who_ls                    object
%whos                      oct
%xdel                      open
%xmode                     or
ArithmeticError            ord
AssertionError             pass
AttributeError             pow
BaseException              print
BufferError                property
BytesWarning               quit
DeprecationWarning         raise
EOFError                   range
Ellipsis                   raw_input
EnvironmentError           reduce
Exception                  reload
False                      repr
FloatingPointError         return
FutureWarning              reversed
GeneratorExit              round
IOError                    set
ImportError                setattr
ImportWarning              slice
In                         sorted
IndentationError           staticmethod
IndexError                 str
KeyError                   sum
KeyboardInterrupt          super
LookupError                try
MemoryError                tuple
NameError                  type
None                       unichr
NotImplemented             unicode
NotImplementedError        vars
OSError                    while
Out                        with
OverflowError              xrange
PendingDeprecationWarning  yield
ReferenceError             zip
RuntimeError               
:       keyword = raw_input("Enter the keyword to scrap: ")
:       name=
Display all 313 possibilities? (y or n)
%%!                        RuntimeWarning
%%HTML                     StandardError
%%SVG                      StopIteration
%%bash                     SyntaxError
%%capture                  SyntaxWarning
%%debug                    SystemError
%%file                     SystemExit
%%html                     TabError
%%javascript               True
%%latex                    TypeError
%%perl                     UnboundLocalError
%%prun                     UnicodeDecodeError
%%pypy                     UnicodeEncodeError
%%python                   UnicodeError
%%python2                  UnicodeTranslateError
%%python3                  UnicodeWarning
%%ruby                     UserWarning
%%script                   ValueError
%%sh                       Warning
%%svg                      ZeroDivisionError
%%sx                       _
%%system                   __
%%time                     __IPYTHON__
%%timeit                   __IPYTHON__active
%%writefile                ___
%alias                     __builtin__
%alias_magic               __debug__
%autocall                  __doc__
%autoindent                __import__
%automagic                 __name__
%bookmark                  __package__
%cat                       _dh
%cd                        _i
%clear                     _i1
%colors                    _ih
%config                    _ii
%cp                        _iii
%cpaste                    _oh
%debug                     _sh
%dhist                     abs
%dirs                      all
%doctest_mode              and
%ed                        any
%edit                      apply
%env                       as
%gui                       assert
%hist                      basestring
%history                   bin
%install_default_config    bool
%install_ext               break
%install_profiles          buffer
%killbgscripts             bytearray
%ldir                      bytes
%less                      callable
%lf                        chr
%lk                        class
%ll                        classmethod
%load                      cmp
%load_ext                  coerce
%loadpy                    compile
%logoff                    complex
%logon                     continue
%logstart                  copyright
%logstate                  credits
%logstop                   def
%ls                        del
%lsmagic                   delattr
%lx                        dict
%macro                     dir
%magic                     divmod
%man                       dreload
%matplotlib                elif
%mkdir                     else
%more                      enumerate
%mv                        eval
%notebook                  except
%page                      exec
%paste                     execfile
%pastebin                  exit
%pdb                       file
%pdef                      filter
%pdoc                      finally
%pfile                     float
%pinfo                     for
%pinfo2                    format
%popd                      from
%pprint                    frozenset
%precision                 get_ipython
%profile                   getattr
%prun                      global
%psearch                   globals
%psource                   hasattr
%pushd                     hash
%pwd                       help
%pycat                     hex
%pylab                     id
%quickref                  if
%recall                    import
%rehashx                   in
%reload_ext                input
%rep                       int
%rerun                     intern
%reset                     is
%reset_selective           isinstance
%rm                        issubclass
%rmdir                     iter
%run                       lambda
%save                      len
%sc                        license
%store                     list
%sx                        locals
%system                    long
%tb                        map
%time                      max
%timeit                    memoryview
%unalias                   min
%unload_ext                next
%who                       not
%who_ls                    object
%whos                      oct
%xdel                      open
%xmode                     or
ArithmeticError            ord
AssertionError             pass
AttributeError             pow
BaseException              print
BufferError                property
BytesWarning               quit
DeprecationWarning         raise
EOFError                   range
Ellipsis                   raw_input
EnvironmentError           reduce
Exception                  reload
False                      repr
FloatingPointError         return
FutureWarning              reversed
GeneratorExit              round
IOError                    set
ImportError                setattr
ImportWarning              slice
In                         sorted
IndentationError           staticmethod
IndexError                 str
KeyError                   sum
KeyboardInterrupt          super
LookupError                try
MemoryError                tuple
NameError                  type
None                       unichr
NotImplemented             unicode
NotImplementedError        vars
OSError                    while
Out                        with
OverflowError              xrange
PendingDeprecationWarning  yield
ReferenceError             zip
RuntimeError               
:       name='redditscraper'
:       oop_url=
Display all 313 possibilities? (y or n)
%%!                        RuntimeWarning
%%HTML                     StandardError
%%SVG                      StopIteration
%%bash                     SyntaxError
%%capture                  SyntaxWarning
%%debug                    SystemError
%%file                     SystemExit
%%html                     TabError
%%javascript               True
%%latex                    TypeError
%%perl                     UnboundLocalError
%%prun                     UnicodeDecodeError
%%pypy                     UnicodeEncodeError
%%python                   UnicodeError
%%python2                  UnicodeTranslateError
%%python3                  UnicodeWarning
%%ruby                     UserWarning
%%script                   ValueError
%%sh                       Warning
%%svg                      ZeroDivisionError
%%sx                       _
%%system                   __
%%time                     __IPYTHON__
%%timeit                   __IPYTHON__active
%%writefile                ___
%alias                     __builtin__
%alias_magic               __debug__
%autocall                  __doc__
%autoindent                __import__
%automagic                 __name__
%bookmark                  __package__
%cat                       _dh
%cd                        _i
%clear                     _i1
%colors                    _ih
%config                    _ii
%cp                        _iii
%cpaste                    _oh
%debug                     _sh
%dhist                     abs
%dirs                      all
%doctest_mode              and
%ed                        any
%edit                      apply
%env                       as
%gui                       assert
%hist                      basestring
%history                   bin
%install_default_config    bool
%install_ext               break
%install_profiles          buffer
%killbgscripts             bytearray
%ldir                      bytes
%less                      callable
%lf                        chr
%lk                        class
%ll                        classmethod
%load                      cmp
%load_ext                  coerce
%loadpy                    compile
%logoff                    complex
%logon                     continue
%logstart                  copyright
%logstate                  credits
%logstop                   def
%ls                        del
%lsmagic                   delattr
%lx                        dict
%macro                     dir
%magic                     divmod
%man                       dreload
%matplotlib                elif
%mkdir                     else
%more                      enumerate
%mv                        eval
%notebook                  except
%page                      exec
%paste                     execfile
%pastebin                  exit
%pdb                       file
%pdef                      filter
%pdoc                      finally
%pfile                     float
%pinfo                     for
%pinfo2                    format
%popd                      from
%pprint                    frozenset
%precision                 get_ipython
%profile                   getattr
%prun                      global
%psearch                   globals
%psource                   hasattr
%pushd                     hash
%pwd                       help
%pycat                     hex
%pylab                     id
%quickref                  if
%recall                    import
%rehashx                   in
%reload_ext                input
%rep                       int
%rerun                     intern
%reset                     is
%reset_selective           isinstance
%rm                        issubclass
%rmdir                     iter
%run                       lambda
%save                      len
%sc                        license
%store                     list
%sx                        locals
%system                    long
%tb                        map
%time                      max
%timeit                    memoryview
%unalias                   min
%unload_ext                next
%who                       not
%who_ls                    object
%whos                      oct
%xdel                      open
%xmode                     or
ArithmeticError            ord
AssertionError             pass
AttributeError             pow
BaseException              print
BufferError                property
BytesWarning               quit
DeprecationWarning         raise
EOFError                   range
Ellipsis                   raw_input
EnvironmentError           reduce
Exception                  reload
False                      repr
FloatingPointError         return
FutureWarning              reversed
GeneratorExit              round
IOError                    set
ImportError                setattr
ImportWarning              slice
In                         sorted
IndentationError           staticmethod
IndexError                 str
KeyError                   sum
KeyboardInterrupt          super
LookupError                try
MemoryError                tuple
NameError                  type
None                       unichr
NotImplemented             unicode
NotImplementedError        vars
OSError                    while
Out                        with
OverflowError              xrange
PendingDeprecationWarning  yield
ReferenceError             zip
RuntimeError               
:       oop_url='https://www.reddit.com/r/'+keyword
:       start_urls 
Display all 341 possibilities? (y or n)
%%!
%%HTML
%%SVG
%%bash
%%capture
%%debug
%%file
%%html
%%javascript
%%latex
%%perl
%%prun
%%pypy
%%python
%%python2
%%python3
%%ruby
%%script
%%sh
%%svg
%%sx
%%system
%%time
%%timeit
%%writefile
%alias
%alias_magic
%autocall
%autoindent
%automagic
%bookmark
%cat
%cd
%clear
%colors
%config
%cp
%cpaste
%debug
%dhist
%dirs
%doctest_mode
%ed
%edit
%env
%gui
%hist
%history
%install_default_config
%install_ext
%install_profiles
%killbgscripts
%ldir
%less
%lf
%lk
%ll
%load
%load_ext
%loadpy
%logoff
%logon
%logstart
%logstate
%logstop
%ls
%lsmagic
%lx
%macro
%magic
%man
%matplotlib
%mkdir
%more

继续……

【问题讨论】:

  • 在常规终端中,您可以执行python -c <paste code>
  • 当您尝试使用 %cpaste 运行 ipython 时收到什么错误?我们可以看看你试图运行什么吗?
  • “但它不起作用”不足以描述问题。
  • 抱歉,我用更多信息编辑了问题。
  • 他们在使用标签?布鲁格。不过,我的印象是粘贴标签应该起作用,而不是触发代码完成。

标签: python linux terminal ipython


【解决方案1】:

%paste 为我工作。

在编辑器中,我使用制表符缩进

def foo(x):
--->return x

复制一份

In [892]: %paste
def foo(x):
        return x

## -- End pasted text --

In [893]: foo(2)
Out[893]: 2

实际上ctrl v 粘贴,有和没有%cpaste 都可以。这让我想知道是否还有其他事情发生。您来自 github 的粘贴不保留任何有趣的字符。

好的,导致问题的不是缩进标签,而是内部标签。如果我在函数中再添加 2 个选项卡

def foo(x):
    x   =   34
    return x

%paste 工作正常,但在ctrl v 期间,内部选项卡会触发选项卡完成。

在你的 ipython 会话中试试这个

<tab>x<tab>=3

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2020-12-27
    • 2011-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多