#!/usr/bin/env python # coding: utf-8 # # Ipython 解释器 # ## 进入ipython # 通常我们并不使用**Python**自带的解释器,而是使用另一个比较方便的解释器——**ipython**解释器,命令行下输入: # # ipython # # 即可进入**ipython**解释器。 # # 所有在**python**解释器下可以运行的代码都可以在**ipython**解释器下运行: # In[1]: print "hello, world" # 可以进行简单赋值操作: # In[2]: a = 1 # 直接在解释器中输入变量名,会显示变量的值(不需要加`print`): # In[3]: a # In[4]: b = [1, 2, 3] # ## ipython magic命令 # **ipython**解释器提供了很多以百分号`%`开头的`magic`命令,这些命令很像linux系统下的命令行命令(事实上有些是一样的)。 # # 查看所有的`magic`命令: # In[5]: get_ipython().run_line_magic('lsmagic', '') # `line magic` 以一个百分号开头,作用与一行; # # `cell magic` 以两个百分号开头,作用于整个cell。 # # 最后一行`Automagic is ON, % prefix IS NOT needed for line magics.`说明在此时即使不加上`%`也可以使用这些命令。 # # 使用 `whos` 查看当前的变量空间: # In[6]: get_ipython().run_line_magic('whos', '') # 使用 `reset` 重置当前变量空间: # In[7]: get_ipython().run_line_magic('reset', '-f') # 再查看当前变量空间: # In[8]: get_ipython().run_line_magic('whos', '') # 使用 `pwd` 查看当前工作文件夹: # In[9]: get_ipython().run_line_magic('pwd', '') # 使用 `mkdir` 产生新文件夹: # In[10]: get_ipython().run_line_magic('mkdir', 'demo_test') # 使用 `cd` 改变工作文件夹: # In[11]: get_ipython().run_line_magic('cd', 'demo_test/') # 使用 `writefile` 将cell中的内容写入文件: # In[12]: get_ipython().run_cell_magic('writefile', 'hello_world.py', 'print "hello world"\n') # 使用 `ls` 查看当前工作文件夹的文件: # In[13]: get_ipython().run_line_magic('ls', '') # 使用 `run` 命令来运行这个代码: # In[14]: get_ipython().run_line_magic('run', 'hello_world.py') # 删除这个文件: # In[15]: import os os.remove('hello_world.py') # 查看当前文件夹,`hello_world.py` 已被删除: # In[16]: get_ipython().run_line_magic('ls', '') # 返回上一层文件夹: # In[17]: get_ipython().run_line_magic('cd', '..') # 使用 `rmdir` 删除文件夹: # In[18]: get_ipython().run_line_magic('rmdir', 'demo_test') # 使用 `hist` 查看历史命令: # In[19]: get_ipython().run_line_magic('hist', '') # ## ipython 使用 # 使用 `?` 查看函数的帮助: # In[20]: get_ipython().run_line_magic('pinfo', 'sum') # 使用 `??` 查看函数帮助和函数源代码(如果是用**python**实现的): # In[21]: # 导入numpy和matplotlib两个包 get_ipython().run_line_magic('pylab', '') # 查看其中sort函数的帮助 get_ipython().run_line_magic('pinfo2', 'sort') # **ipython** 支持使用 `` 键自动补全命令。 # 使用 `_` 使用上个cell的输出结果: # In[22]: a = 12 a # In[23]: _ + 13 # 可以使用 `!` 来执行一些系统命令。 # In[24]: get_ipython().system('ping baidu.com') # 当输入出现错误时,**ipython**会指出出错的位置和原因: # In[25]: 1 + "hello"