我怎样才能快速测试几行?

时间:2016-06-20 15:49:46

标签: python linux terminal ipython

假设我正在浏览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

它继续.....

1 个答案:

答案 0 :(得分:0)

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粘贴,有和没有def foo(x): x = 34 return x 也可以。这让我想知道是否还有其他事情发生。来自github的粘贴不会保留任何有趣的角色。

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

%paste

ctrl v工作正常,但在<tab>x<tab>=3 期间,内部标签会触发标签页完成。

在ipython会话中尝试此操作

jQuery(document).ready(function(jQ) {
  jQ('#tenure_month').keyup( calc );
jQ('#cmpnd_anually').keyup( calcu );
var to_years;
 function calc() {    

to_years = jQ('#tenure_month').val();
    to_years = parseFloat(to_years) / 12;
    to_years = to_years.toFixed(1);
  jQ('#years').val(to_years);

};

 function calcu() {
var dep;
var rate_int;
var cmp_int;
dep = jQ('#deposit_amt').val(); 
dep = parseFloat(dep);

rate_int = parseFloat(jQ('#rate_int').val() / 400));
rate_int = rate_int.toFixed(1);

cmp_int =  dep * (1 + rate_int) ^ 4 * t_years;
  jQ('#cmpnd_anually').val(cmp_int);

};  
});