day01- IPython

#插入图像
#在markdown格式下
#输入![](当前路径下图片名)就能展示图片#如下图

这里写图片描述

这里写图片描述

目录

一、启动程序

二、IPython的帮助文档

1. 使用help()

2. 使用?

3. tab自动补全

三、IPython魔法命令

1. 运行外部Python文件

2. 运行计时

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

4. 执行Linux指令

5. 更多魔法命令

一、启动程序

执行以下命令:

jupyter notebook

[NotebookApp] Serving notebooks from local directory: /home/nanfengpo

[NotebookApp] 0 active kernels

[NotebookApp] The IPython Notebook is running at: http://localhost:8888/

[NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).

注意以下几点:
- 打开地址为当前bash的目录,默认的根目录
- 浏览器地址为http://localhost:8888/
- 通过control -C终止jupyter程序

几个基本操作:
- 双击D:删除当前cell
- 单击M:转为markdown文档
- markdown文档下运行变为预览模式

二、IPython的帮助文档

1. 使用help()

通过以下命令来获得帮助文档:

help(len)

Help on built-in function len in module builtins:

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

help(len)
Help on built-in function len in module builtins:

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

help(type)
Help on class type in module builtins:

class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
 |  
 |  Methods defined here:
 |  
 |  __call__(self, /, *args, **kwargs)
 |      Call self as a function.
 |  
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |  
 |  __dir__(...)
 |      __dir__() -> list
 |      specialized __dir__ implementation for types
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __instancecheck__(...)
 |      __instancecheck__() -> bool
 |      check if an object is an instance
 |  
 |  __new__(*args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __prepare__(...)
 |      __prepare__() -> dict
 |      used to create the namespace for the class statement
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __setattr__(self, name, value, /)
 |      Implement setattr(self, name, value).
 |  
 |  __sizeof__(...)
 |      __sizeof__() -> int
 |      return memory consumption of the type object
 |  
 |  __subclasscheck__(...)
 |      __subclasscheck__() -> bool
 |      check if a class is a subclass
 |  
 |  __subclasses__(...)
 |      __subclasses__() -> list of immediate subclasses
 |  
 |  mro(...)
 |      mro() -> list
 |      return a type's method resolution order
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __abstractmethods__
 |  
 |  __dict__
 |  
 |  __text_signature__
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __base__ = <class 'object'>
 |      The most base type
 |  
 |  __bases__ = (<class 'object'>,)
 |  
 |  __basicsize__ = 864
 |  
 |  __dictoffset__ = 264
 |  
 |  __flags__ = -2146675712
 |  
 |  __itemsize__ = 40
 |  
 |  __mro__ = (<class 'type'>, <class 'object'>)
 |  
 |  __weakrefoffset__ = 368

2. 使用?

或者使用问号:

len?

len?

还可以应用到自定义的变量和自定义的函数上来返回帮助文档

此外,使用两个??可以把函数的源代码显示出来

def square(num):
    '''求解数字的平方'''
    ret = num**2
    return ret
square?
# ?? 问的更深了,显示源码
square??

3. tab自动补全

敲击tab键能自动补全(与cmd补全方式一样)

L.

也可以在import的时候自动补全

import nu

import random
from PIL import Image
import numpy as np

三、IPython魔法命令

1. 运行外部Python文件

使用下面命令运行外部python文件(默认是当前目录,最好加上绝对路径)

%run *.py

例如在当前目录下有一个myscript.py文件:

def square(x):
“”“square a number”“”
return x ** 2

for N in range(1, 4):
print(N, “squared is”, square(N))

%run hello.py    #jupyter里面文件相对路径
来自外部文件的打印
a + b 运行结果: 1536
         1,         1
         2,         3
         5,         8
        13,        21
        34,        55
print(a,b,c)
1024 512 1536
fabnacci(20)
         1,         1
         2,         3
         5,         8
        13,        21
        34,        55
        89,       144
       233,       377
       610,       987
      1597,      2584
      4181,      6765
     10946,     17711
     28657,     46368
     75025,    121393
    196418,    317811
    514229,    832040
   1346269,   2178309
   3524578,   5702887
   9227465,  14930352
  24157817,  39088169
  63245986, 102334155
# 执行桌面上的python文件
%run C:/Users/softpo.DESKTOP-PN692CT/Desktop/hello.py   #本地文件 绝对路径  注意斜杠方向
来自外部文件的打印
a + b 运行结果: 1536
         1,         1
         2,         3
         5,         8
        13,        21
        34,        55

我们可以通过下面命令执行它:

%run myscript.py

尤其要注意的是,当我们使用魔法命令执行了一个外部文件时,该文件的函数就能在当前会话中使用

square(5)

#调用外部文件中定义的方法

2. 运行计时

用下面命令计算statement的运行时间:

%time statement

%time fabnacci(100)
         1,         1
         2,         3
         5,         8
        13,        21
        34,        55
        89,       144
       233,       377
       610,       987
      1597,      2584
      4181,      6765
     10946,     17711
     28657,     46368
     75025,    121393
    196418,    317811
    514229,    832040
   1346269,   2178309
   3524578,   5702887
   9227465,  14930352
  24157817,  39088169
  63245986, 102334155
 165580141, 267914296
 433494437, 701408733
1134903170,1836311903
2971215073,4807526976
7778742049,12586269025
20365011074,32951280099
53316291173,86267571272
139583862445,225851433717
365435296162,591286729879
956722026041,1548008755920
2504730781961,4052739537881
6557470319842,10610209857723
17167680177565,27777890035288
44945570212853,72723460248141
117669030460994,190392490709135
308061521170129,498454011879264
806515533049393,1304969544928657
2111485077978050,3416454622906707
5527939700884757,8944394323791464
14472334024676221,23416728348467685
37889062373143906,61305790721611591
99194853094755497,160500643816367088
259695496911122585,420196140727489673
679891637638612258,1100087778366101931
1779979416004714189,2880067194370816120
4660046610375530309,7540113804746346429
12200160415121876738,19740274219868223167
31940434634990099905,51680708854858323072
83621143489848422977,135301852344706746049
218922995834555169026,354224848179261915075
573147844013817084101,927372692193078999176
1500520536206896083277,2427893228399975082453
3928413764606871165730,6356306993006846248183
10284720757613717413913,16641027750620563662096
26925748508234281076009,43566776258854844738105
70492524767089125814114,114059301025943970552219
184551825793033096366333,298611126818977066918552
483162952612010163284885,781774079430987230203437
1264937032042997393488322,2046711111473984623691759
3311648143516982017180081,5358359254990966640871840
8670007398507948658051921,14028366653498915298923761
22698374052006863956975682,36726740705505779255899443
59425114757512643212875125,96151855463018422468774568
155576970220531065681649693,251728825683549488150424261
407305795904080553832073954,659034621587630041982498215
1066340417491710595814572169,1725375039079340637797070384
2791715456571051233611642553,4517090495650391871408712937
7308805952221443105020355490,11825896447871834976429068427
19134702400093278081449423917,30960598847965113057878492344
50095301248058391139327916261,81055900096023504197206408605
131151201344081895336534324866,212207101440105399533740733471
343358302784187294870275058337,555565404224292694404015791808
898923707008479989274290850145,1454489111232772683678306641953
2353412818241252672952597492098,3807901929474025356630904134051
6161314747715278029583501626149,9969216677189303386214405760200
16130531424904581415797907386349,26099748102093884802012313146549
42230279526998466217810220532898,68330027629092351019822533679447
110560307156090817237632754212345,178890334785183168257455287891792
289450641941273985495088042104137,468340976726457153752543329995929
757791618667731139247631372100066,1226132595394188293000174702095995
1983924214061919432247806074196061,3210056809456107725247980776292056
5193981023518027157495786850488117,8404037832974134882743767626780173
13598018856492162040239554477268290,22002056689466296922983322104048463
35600075545958458963222876581316753,57602132235424755886206198685365216
93202207781383214849429075266681969,150804340016807970735635273952047185
244006547798191185585064349218729154,394810887814999156320699623170776339
638817435613190341905763972389505493,1033628323428189498226463595560281832
1672445759041379840132227567949787325,2706074082469569338358691163510069157
4378519841510949178490918731459856482,7084593923980518516849609894969925639
11463113765491467695340528626429782121,18547707689471986212190138521399707760
30010821454963453907530667147829489881,48558529144435440119720805669229197641
78569350599398894027251472817058687522,127127879743834334146972278486287885163
205697230343233228174223751303346572685,332825110087067562321196029789634457848
538522340430300790495419781092981030533,871347450517368352816615810882615488381
1409869790947669143312035591975596518914,2281217241465037496128651402858212007295
3691087032412706639440686994833808526209,5972304273877744135569338397692020533504
9663391306290450775010025392525829059713,15635695580168194910579363790217849593217
25299086886458645685589389182743678652930,40934782466626840596168752972961528246147
66233869353085486281758142155705206899077,107168651819712326877926895128666735145224
173402521172797813159685037284371942044301,280571172992510140037611932413038677189525
Wall time: 2.96 ms

用下面命令计算statement的平均运行时间:

%timeit statement

timeit会多次运行statement,最后得到一个更为精准的预期运行时间

%timeit square(100000)  #std是标准方差  代表里算程度
486 ns ± 41.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

可以使用两个百分号来测试多行代码的平均运行时间:

`
%%timeit

statement1

statement2

statement3

`

%%timeit
square(10000)
fabnacci(10)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-3-2a35e364c7b1> in <module>()
----> 1 get_ipython().run_cell_magic('timeit', '', 'square(10000)\nfabnacci(10)')


c:\program files\python3.6\lib\site-packages\IPython\core\interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2165             magic_arg_s = self.var_expand(line, stack_depth)
   2166             with self.builtin_trap:
-> 2167                 result = fn(magic_arg_s, cell)
   2168             return result
   2169 


<decorator-gen-62> in timeit(self, line, cell, local_ns)


c:\program files\python3.6\lib\site-packages\IPython\core\magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):


c:\program files\python3.6\lib\site-packages\IPython\core\magics\execution.py in timeit(self, line, cell, local_ns)
   1096             for index in range(0, 10):
   1097                 number = 10 ** index
-> 1098                 time_number = timer.timeit(number)
   1099                 if time_number >= 0.2:
   1100                     break


c:\program files\python3.6\lib\site-packages\IPython\core\magics\execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:


<magic-timeit> in inner(_it, _timer)


NameError: name 'square' is not defined
记住:
- %time一般用于耗时长的代码段
- %timeit一般用于耗时短的代码段

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

快速查看当前会话的所有变量与函数名称:

%who

%who
Image    a   b   c   fabnacci    np  square  

查看当前会话的所有变量与函数名称的详细信息:

%whos

%whos
Variable   Type        Data/Info
--------------------------------
Image      module      <module 'PIL.Image' from <...>packages\\PIL\\Image.py'>
a          int         1024
b          int         512
c          int         1536
fabnacci   function    <function fabnacci at 0x000001AAC9484AE8>
np         module      <module 'numpy' from 'C:\<...>ges\\numpy\\__init__.py'>
square     function    <function square at 0x000001AAC90B7E18>

返回一个字符串列表,里面元素是当前会话的所有变量与函数名称:

%who_ls

%who_ls
['Image', 'a', 'b', 'c', 'fabnacci', 'np', 'square']

4. 执行Linux指令

Linux指令:

$ echo “hello world” # echo is like Python’s print function
hello world

$ pwd # pwd = print working directory
/home/jake # this is the “path” that we’re sitting in

$ ls # ls = list working directory contents
notebooks projects

$ mkdir mm
/home/jake/projects

$touch txt
!touch /home/nanfengpo/Desktop/xx/hello.txt

在Linux指令之前加上 <font size = 5 color = green>!</font>,即可在ipython当中执行Linux指令。

注意会将标准输出以字符串形式返回

!echo 'Hello'
'Hello'
password = !echo %password%
password
['lbrv3bgb']
# linux 指令,在windows下不能执行
!pwd
'pwd' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
!ls
'ls' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
!dir
 驱动器 C 中的卷没有标签。
 卷的序列号是 CA7F-87AA

 C:\Users\softpo.DESKTOP-PN692CT\Analysis\shh1803\Data-Analysis\1-IPython\softpo 的目录

2018/07/11  10:56    <DIR>          .
2018/07/11  10:56    <DIR>          ..
2018/07/11  09:52    <DIR>          .ipynb_checkpoints
2018/06/26  20:47            15,933 1.jpg
2018/04/11  16:41            37,556 2.jpg
2018/07/11  10:38               295 hello.py
2018/07/11  10:56         2,708,745 IPython.ipynb
               4 个文件      2,762,529 字节
               3 个目录 108,507,070,464 可用字节
!mkdir test
# touch  linux下创建文件
!touch test/hello.py
'touch' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
# windows下创建文件夹,查找创建指令,代码中使用!+指令

5. 更多魔法命令

列出所有魔法命令

lsmagic

查看魔法命令的文档:
使用?

%ls
 驱动器 C 中的卷没有标签。
 卷的序列号是 CA7F-87AA

 C:\Users\softpo.DESKTOP-PN692CT\Analysis\shh1803\Data-Analysis\1-IPython\softpo 的目录

2018/07/11  11:02    <DIR>          .
2018/07/11  11:02    <DIR>          ..
2018/07/11  09:52    <DIR>          .ipynb_checkpoints
2018/06/26  20:47            15,933 1.jpg
2018/04/11  16:41            37,556 2.jpg
2018/07/11  10:38               295 hello.py
2018/07/11  11:02         2,711,095 IPython.ipynb
2018/07/11  10:59    <DIR>          test
               4 个文件      2,764,879 字节
               4 个目录 108,501,663,744 可用字节
%lsmagic
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.
lsmagic
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.

四、notebook的快捷键

1、命令模式

• Enter : 转入编辑模式 
• Shift-Enter : 运行本单元,选中下个单元
• Ctrl-Enter : 运行本单元,选中本单元
• Alt-Enter : 运行本单元,在下面插入一单元
a = 1024
# 注释
• Y : 单元转入代码状态
• M :单元转入markdown状态

• A : 在上方插入新单元
• B : 在下方插入新单元

2、编辑模式 ( Enter 键启动)

• Tab : 代码补全或缩进
• Shift-Tab : 提示
np.random.randint(low = 10,high=100,size = 1)
array([72])



• Ctrl-A : 全选
• Ctrl-Z : 复原

============================================

练习:

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

  • 简单代码
  • 分支
  • 循环
  • 函数

============================================

猜你喜欢

转载自blog.csdn.net/weixin_41853490/article/details/81119018