IPython

#cell :写代码的地方
print(123)
#快捷键: ctrl+enter  运行键
123

目录

一、启动程序

二、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程序
#1. 在anacaond可视化界面 点击jupyter notebook启动、
#2.在黑屏终端启动, 输入 jupyter notebook 即可 也会弹出来一个网页

几个基本操作:

  • 双击D:删除当前cell
  • 单击M:转为markdown文档
  • markdown文档下运行变为预览模式
#新建一个cell   快捷键b
print(123456)
#绿色叫编辑状态
#如果想插入的话, 砸门就必须是蓝色的状态
123456
#快捷键a向上插入一个cell 
#

二、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(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. 使用?

或者使用问号:

len?

len?
len??

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

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

#随意定义一个函数
def square(num):
    '''
    该方法返回的是一个数的平方
    '''
    return num * num
square(5)
25
square?
square??

3. tab自动补全

敲击tab键能自动补全

L.

#快捷键  tab  自动补全
import time
import sys
from sklearn.neighbors import KNeighborsClassifier

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

三、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 myscript.py

%run "./1810.py" 
#使用%run 运行外部的python文件  run 后面跟着是路径   相对路径和绝对路径
123
%run "C:\Users\wang\Desktop\bj1810\day01\1-IPython\softpo\1810.py"
123

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

square(5)

2. 运行计时

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

%time statement

def calsum(num):
    result = 0
    for i in range(1, num + 1):
        result += i
        for j in range(1, num + 1):
            result -= 0
            
%time calsum(1000)
Wall time: 133 ms
%timeit calsum(1000)
#平均运行时间
68.3 ms ± 5.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

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

%timeit statement

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

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

`
%%timeit

statement1

statement2

statement3

`

记住:

  • %time一般用于耗时长的代码段
  • %timeit一般用于耗时短的代码段
%%timeit 

print("hello")
calsum(100)
calsum(1000)
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
95.6 ms ± 18.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

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

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

%who

%who
calsum	 square	 

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

%whos

%whos
Variable   Type        Data/Info
--------------------------------
calsum     function    <function calsum at 0x000000000D491950>
square     function    <function square at 0x000000000578BD90>

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

%who_ls

%who_ls
['calsum', '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指令之前加上 !,即可在ipython当中执行Linux指令。

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

!echo "hello"
"hello"
!pwd
'pwd' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

5. 更多魔法命令

列出所有魔法命令

lsmagic

%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.
%time %matplotlib

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

四、notebook的快捷键

1、命令模式

• Enter : 转入编辑模式 
• Shift-Enter : 运行本单元,选中下个单元
• Ctrl-Enter : 运行本单元,选中本单元
• Alt-Enter : 运行本单元,在下面插入一单元
print(123)
123


• Y : 单元转入代码状态
• M :单元转入markdown状态

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

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

• Tab : 代码补全或缩进
• Shift-Tab : 提示

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

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

练习:

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值