iPython使用

一、启动程序

命令:jupyter notebook

这个命令可以启动jupyter的交互服务器,并且把当前目录作为映射打开一个web界面,加载映射的目录结构

【注意】如果这个命令提示错误,检测环境变量还有anaconda是否安装完全(如果不完全:手动安装pip install jupyter)

In [ ]:

二、IPython的帮助文档

1、使用help()

In [1]:
help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

In [2]:
help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |  
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.n
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(self, value, /)
 |      Return self*value.
 |  
 |  __setitem__(self, key, value, /)
 |      Set self[key] to value.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -> None -- append object to end
 |  
 |  clear(...)
 |      L.clear() -> None -- remove all items from L
 |  
 |  copy(...)
 |      L.copy() -> list -- a shallow copy of L
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -> None -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

2、使用"?"

In [3]:
len?
In [4]:
list??

?显示这个函数的帮助文档,“??”显示帮助文档和源码(如果不开源则不显示)

In [5]:
def sqaure(a):
    "求平方"
    return a**2
In [6]:
sqaure??

3、使用"tab"键自动补全

In [7]:
import
pass
  File "<ipython-input-7-b14750c35a54>", line 1
    import
          ^
SyntaxError: invalid syntax


三、IPython魔法命令

1、运行在外部Python文件

%run xx.py

In [8]:
%run hello.py
In [9]:
hello()
hello
In [10]:
a
Out[10]:
100

当魔法指令运行一个外部文件以后,该文件的函数就可以在cell会话中使用

2、查看运行计时

%time python语句
查看程序运行的时间

In [11]:
%time print("hello")
hello
Wall time: 0 ns
In [12]:
def func1():
    res = 0
    for i in range(0,1000):
        res += 1
        for j in range(1000):
            res -= 1
        
        
In [13]:
%time func1()
Wall time: 86.9 ms

%timeit statement 用于计算statement的平均运行时间 %timeit 会多次运行statement,最后得到一个比较准确的运行时间

In [14]:
%timeit func1()
71.1 ms ± 864 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit 可以测试多行代码的平均运行时间 %%timeit statement1 statement2 ...

In [15]:
%%timeit
print("xxxx")
func1()
len([1,1,2,4,5])
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
xxxx
84.5 ms ± 4.72 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%time 一般用于耗时比较长的代码段

%timeit 一般用于耗时比较短的代码段

In [ ]:

3、查看当前会话中所有的变量与函数

查看单签会话的所有变量与函数的详细信息 %whos

In [16]:
%whos
Variable   Type        Data/Info
--------------------------------
a          int         100
func1      function    <function func1 at 0x000001807E3902F0>
hello      function    <function hello at 0x000001807E346730>
sqaure     function    <function sqaure at 0x000001807E346C80>
In [17]:
%who_ls
Out[17]:
['a', 'func1', 'hello', 'sqaure']

4、执行系统终端指令

写法:!指令名(在windows系统下应该执行Windows的系统命令,linux要执行对应的Linux版本的系统zhil)

In [18]:
!ipconfig
Windows IP 配置


无线局域网适配器 本地连接* 4:

   媒体状态  . . . . . . . . . . . . : 媒体已断开连接
   连接特定的 DNS 后缀 . . . . . . . : 

无线局域网适配器 本地连接* 5:

   媒体状态  . . . . . . . . . . . . : 媒体已断开连接
   连接特定的 DNS 后缀 . . . . . . . : 

以太网适配器 以太网:

   连接特定的 DNS 后缀 . . . . . . . : 
   本地链接 IPv6 地址. . . . . . . . : fe80::9f9:2416:eb5a:fe7a%15
   IPv4 地址 . . . . . . . . . . . . : 10.8.153.36
   子网掩码  . . . . . . . . . . . . : 255.255.255.0
   默认网关. . . . . . . . . . . . . : 10.8.153.254

以太网适配器 VMware Network Adapter VMnet1:

   连接特定的 DNS 后缀 . . . . . . . : 
   本地链接 IPv6 地址. . . . . . . . : fe80::a55b:e386:ead3:7c94%2
   IPv4 地址 . . . . . . . . . . . . : 192.168.159.1
   子网掩码  . . . . . . . . . . . . : 255.255.255.0
   默认网关. . . . . . . . . . . . . : 

以太网适配器 VMware Network Adapter VMnet8:

   连接特定的 DNS 后缀 . . . . . . . : 
   本地链接 IPv6 地址. . . . . . . . : fe80::7d1e:30d1:7ea9:2fbf%17
   IPv4 地址 . . . . . . . . . . . . : 192.168.48.1
   子网掩码  . . . . . . . . . . . . : 255.255.255.0
   默认网关. . . . . . . . . . . . . : 

无线局域网适配器 WLAN:

   媒体状态  . . . . . . . . . . . . : 媒体已断开连接
   连接特定的 DNS 后缀 . . . . . . . : 
In [19]:
!cd ..
In [ ]:

5、更多魔法指令或者cmd

列出所有的魔法指令 %lsmagic

In [20]:
%lsmagic
Out[20]:
Available line magics:
%alias  %alias_magic  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %colors  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %matplotlib  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %popd  %pprint  %precision  %profile  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode

Available cell magics:
%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile

Automagic is ON, % prefix IS NOT needed for line magics.
In [21]:
%cd?

四、快捷键

In [ ]:

1、命令模式

enter: 转入编辑模式

shift+enter:运行本行,并且选中下行

ctrl+enter: 运行本行,并且选中本行

alt+enter:运行本行,并且插入一个新的cell

Y:cell转入代码状态

M:cell转入Markdown状态

A: 在上方插入一个新的cell

B:在下方插入一个新的cell

编辑模式下:

tab(或shift+tab)键:提示

ctrl+a:全选当前cell

ctrl+z:撤销

In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:

【练习】

在Jupyter上实现以前的代码,包括:

  • 简单代码
  • 分支
  • 循环
  • 函数
In [ ]:

猜你喜欢

转载自blog.csdn.net/qq_29784441/article/details/80858649
今日推荐