1.1.3 交互工作流:IPython和文本编辑器

测试和理解算法的交互工作:在这个部分我们描述一下用IPython的交互工作流来方便的研究和理解算法。

Python是一门通用语言。与其他的通用语言一样,没有一个绝对权威的工作环境,也不止一种方法使用它。尽管这对新人来说不太好找到适合自己的方式,但是,这使得Python被用于在网站服务器或嵌入设备中编写程序。

本部分的参考文档

IPython用户手册http://ipython.org/ipython-doc/dev/index.html

1.1.3.1 命令行交互

启动ipython:

In [1]:

  1. print('Hello world')
  1. Hello world

在对象后使用?运算符获得帮助:

  1. In [2]: print
  2. Type: builtin_function_or_method
  3. Base Class: <type builtin_function_or_method’>
  4. String Form: <built-in function print>
  5. Namespace: Python builtin
  6. Docstring:
  7. print(value, ..., sep=’ ’, end=’\n’, file=sys.stdout)
  8. Prints the values to a stream, or to sys.stdout by default.
  9. Optional keyword arguments:
  10. file: a file-like object (stream); defaults to the current sys.stdout.
  11. sep: string inserted between values, default a space.
  12. end: string appended after the last value, default a newline.

1.1.3.2 在编辑器中详尽描述算法

在文本编辑器中,创建一个myfile.py文件。在EPD(Enthought Python Distribution)中,你可以从开始按钮使用_Scite。在Python(x,y)中, 你可以使用Spyder。在Ubuntu中, 如果你还没有最喜欢的编辑器,我们建议你安装Stani’s Python editor。在这个文件中,输入如下行:

  1. s = 'Hello world'
  2. print(s)

现在,你可以在IPython中运行它,并研究产生的变量:

In [2]:

  1. %run my_file.py
  1. Hello world

In [3]:

  1. s

Out[3]:

  1. 'Hello world'

In [4]:

  1. %whos
  1. Variable Type Data/Info
  2. &nbsp;-------------&nbsp;---------------
  3. s str Hello world

从脚本到函数

尽管仅使用脚本工作很诱人,即一个满是一个接一个命令的文件,但是要有计划的逐渐从脚本进化到一组函数:

  • 脚本不可复用,函数可复用。
  • 以函数的角度思考,有助于将问题拆分为小代码块。

1.1.3.3 IPython提示与技巧

IPython用户手册包含关于使用IPython的大量信息,但是,为了帮你你更快的入门,这里快速介绍三个有用的功能:历史魔法函数别称tab完成

与Unix Shell相似,IPython支持命令历史。按上下在之前输入的命令间切换:

  1. In [1]: x = 10
  2. In [2]: <UP>
  3. In [2]: x = 10

IPython通过在命令前加%字符的前缀,支持所谓魔法函数。例如,前面部分的函数runwhos都是魔法函数。请注意automagic设置默认是启用,允许你忽略前面的%。因此,你可以只输入魔法函数仍然是有效的。

其他有用的魔法函数:

  • %cd 改变当前目录

In [6]:

  1. cd ..
  1. /Users/cloga/Documents
  • %timeit 允许你使用来自标准库中的timeit模块来记录执行短代码端的运行时间

In [7]:

  1. timeit x = 10
  1. 10000000 loops, best of 3: 26.7 ns per loop
  • %cpaste 允许你粘贴代码,特别是来自网站的代码,前面带有标准的Python提示符 (即 >>>) 或ipython提示符的代码(即 in [3]):
  1. In [5]: cpaste
  2. Pasting code; enter ’--’ alone on the line to stop or use Ctrl-D. :In [3]: timeit x = 10
  3. :--
  4. 10000000 loops, best of 3: 85.9 ns per loop
  5. In [6]: cpaste
  6. Pasting code; enter ’--’ alone on the line to stop or use Ctrl-D. :&gt;&gt;&gt; timeit x = 10
  7. :--
  8. 10000000 loops, best of 3: 86 ns per loop
  • %debug 允许你进入事后除错。也就是说,如果你想要运行的代码抛出了一个异常,使用%debug将在抛出异常的位置进入排错程序。
  1. In [7]: x === 10
  2. File "<ipython-input-6-12fd421b5f28>", line 1
  3. x === 10 ^
  4. SyntaxError: invalid syntax
  5. In [8]: debug
  6. > /home/esc/anaconda/lib/python2.7/site-packages/IPython/core/compilerop.py(87)ast_parse()
  7. 86 and are passed to the built-in compile function."""
  8. ---> 87 return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
  9. 88
  10. ipdb>locals()
  11. {’source’: u’x === 10\n’, ’symbol’: ’exec’, ’self’:
  12. <IPython.core.compilerop.CachingCompiler instance at 0x2ad8ef0>,
  13. ’filename’: ’<ipython-input-6-12fd421b5f28>’}

IPython help

  • 内置的IPython手册可以通过%quickref魔法函数进入。
  • 输入%magic会显示所有可用魔法函数的列表。

而且IPython提供了大量的别称来模拟常见的UNIX命令行工具比如ls等于list files,cp等于copy files以及rm等于remove files。输入alias可以显示所有的别称的列表:

In [5]:

  1. alias
  1. Total number of aliases: 12

Out[5]:

  1. [('cat', 'cat'),
  2. ('cp', 'cp'),
  3. ('ldir', 'ls -F -G -l %l | grep /$'),
  4. ('lf', 'ls -F -l -G %l | grep ^-'),
  5. ('lk', 'ls -F -l -G %l | grep ^l'),
  6. ('ll', 'ls -F -l -G'),
  7. ('ls', 'ls -F -G'),
  8. ('lx', 'ls -F -l -G %l | grep ^-..x'),
  9. ('mkdir', 'mkdir'),
  10. ('mv', 'mv'),
  11. ('rm', 'rm'),
  12. ('rmdir', 'rmdir')]

最后,提一下tab完成功能,我们从IPython手册引用它的描述:

Tab completion, especially for attributes, is a convenient way to explore the structure of any object you’re dealing with. Simply type object_name. <tab>to view the object’s attributes. Besides Python objects and keywords, tab completion also works on file and directory names.</tab>

  1. In [1]: x = 10
  2. In [2]: x.<TAB>
  3. x.bit_length x.conjugate x.denominator x.imag x.numerator x.real
  4. In [3]: x.real.
  5. x.real.bit_length x.real.denominator x.real.numerator x.real.conjugate x.real.imag x.real.real
  6. In [4]: x.real.