IPython的使用

1. IPython简介

ipython是一个python的交互式shell,比默认的python shell好用得多,支持变量自动补全,自动缩进,支持bash shell命令,内置了许多很有用的功能和函数。学习ipython将会让我们以一种更高的效率来使用python。同时它也是利用Python进行科学计算和交互可视化的一个最佳的平台

2. IPython功能

  • 运行ipython控制台
  • 使用ipython作为系统shell
  • 使用历史输入(history)
  • Tab补全
  • 使用%run命令运行脚本
  • 使用%timeit命令快速测量时间
  • 使用%pdb命令快速debug
  • 使用pylab进行交互计算
  • 使用IPython Notebook

3. 安装IPython

ipython支持Python2.7版本或者3.3以上的版本
pip install ipython
在notebook中操作ipython的话,还需要安装jupyter:
pip install jupyter

4. IPython Shell自定义

实例化InteractiveShellEmbed,然后执行此py文件

#!/usr/bin/env python3
import os
import time
from IPython.terminal.prompts import Prompts, Token

class CustomPrompt(Prompts):
    # 自定义输入命令
    def in_prompt_tokens(self, cli=None):

       return [
            (Token.Prompt, 'Demo_in ['),
            (Token.PromptNum, str(self.shell.execution_count)),
            (Token.Prompt, ']: '),
            ]
    # 自定义输出
    def out_prompt_tokens(self):
       return [
            (Token.OutPrompt, 'Demo_out['),
            (Token.OutPromptNum, str(self.shell.execution_count)),
            (Token.OutPrompt, ']: '),
        ]

from traitlets.config import Config

cfg = Config()
cfg.TerminalInteractiveShell.prompts_class=CustomPrompt
cfg.HistoryManager.enabled = True
#cfg.HistoryManager.hist_file = "/tmp/log_history.txt"

# First import the embeddable shell class
from IPython.terminal.embed import InteractiveShellEmbed

# Now create an instance of the embeddable shell. The first argument is a
# string with options exactly as you would type them if you were starting

api_doc = 'index.html'
journal_path = os.path.abspath("log_journal.py")

ipshell = InteractiveShellEmbed(config=cfg,
                         banner1 = "Welcome to Demo Python Shell",
                         banner2 = "Python CLI API documentation is available at \
                             \r\n\033[96m\033[2m"+api_doc+"\
                                 \r\n\033[0mJournal file generates at \033[96m\033[2m"+journal_path+"\
                                     \r\n\033[0mDo not use the file until the session is closed.",
                         enabled = False)   

default_log_file = "log_journal.py"
session_start_time = time.ctime()
log_start_option = " -o -q " + default_log_file
ipshell.run_line_magic('logstart', log_start_option)

# open ipython shell
ipshell()

journal_file_path = os.path.abspath(ipshell.logfile)
JOURNAL_HEADER = f"#-----------------------------------------------------------------\n\
# Start of session at: {session_start_time}\n\
# Current directory: {os.getcwd()}\n\
# Command line: vitis -i\n\
# Journal file: {ipshell.logfile}\n\
# Batch mode: {journal_file_path}\n\
#-----------------------------------------------------------------\n\n\
#!/usr/bin/env python3\n\
"

log_head = "# IPython log file"
ipython_line = "get_ipython()."

data = []
journal_data = []
if(os.path.isfile(journal_file_path)):
    with open(ipshell.logfile, 'r') as input_journal:
        data = input_journal.readlines()

    for line in data:
        if log_head in line:
            journal_data.append(JOURNAL_HEADER)
        elif ipython_line in line:
            ipython_line_read = True
            prev_line = journal_data.pop()
            if "# " not in prev_line:
                journal_data.append(prev_line)
        elif "#[Out]# " in line:
            if ipython_line_read != True:
                journal_data.append(line)
        else:
            ipython_line_read = False
            journal_data.append(line)

    journal_data.append("\n")

    with open(ipshell.logfile, 'w') as output_journal:
        output_journal.writelines(journal_data)
    print(f"Log Journal File is '{journal_file_path}'")

print(f'Demo Python Shell Execution finished. Bye!!')

Python基础知识
Python进阶
IPython的介绍与使用