linux写python补全_Linux为Python添加TAB自动补全和命令历史功能

为Python添加交互模式下TAB自动补全以及命令历史功能。如何操作呢?下面是学习啦小编跟大家分享的是Linux为Python添加TAB自动补全和命令历史功能,欢迎大家来阅读学习~

Linux为Python添加TAB自动补全和命令历史功能

方法/步骤

Linux Python Tab 自动补全方法:

新建Python环境变量配置文件:

vim ~/.pystartup

# Add auto-completion and a stored history file of commands to your Python

# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is

# bound to the Esc key by default (you can change it - see readline docs).

#

# Store the file in ~/.pystartup, and set an environment variable to point

# to it: "export PYTHONSTARTUP=~/.pystartup" in bash.

import atexit

import os

import readline

import rlcompleter

readline.parse_and_bind('tab: complete')

historyPath = os.path.expanduser("~/.pyhistory")

def save_history(historyPath=historyPath):

import readline

readline.write_history_file(historyPath)

if os.path.exists(historyPath):

readline.read_history_file(historyPath)

atexit.register(save_history)

del os, atexit, readline, rlcompleter, save_history, historyPath

设置Python环境变量:

即时生效,重启失效:export PYTHONSTARTUP=~/.pystartup

永久生效:echo "export PYTHONSTARTUP=~/.pystartup" >> /etc/profile

验证:

097bf419c2aa2ab97cac5761022fdba0.png

注:默认补全是ESC。

readline.parse_and_bind('tab: complete') 这条命令用来设定为tab补全。

Windows Python Tab 自动补全方法:

a. 安装python

b. pip install pyreadline

c. 在Python安装路径的Lib文件夹下新建一个tab.py

例如:C:\Program Files (x86)\Python2\Lib

用编辑器编辑:

# Add auto-completion and a stored history file of commands to your Python

# interactive interpreter.

import atexit

import os

import readline

import rlcompleter

import sys

# Tab completion

readline.parse_and_bind('tab: complete')

# history file

histfile = os.path.join("D:\\Tmp\\history\\", ".pythonhistory")

try:

readline.read_history_file(histfile)

except IOError:

pass

atexit.register(readline.write_history_file, histfile)

del os, histfile, readline, rlcompleter

注:

histfile = os.path.join("D:\\Tmp\\history\\", ".pythonhistory") 这个路径可以自定义设置。

d. 输入python就自动加载tab补全

和linux类似,如果想输入python就自动加载tab补全,在系统属性中的环境变量里增加PYTHONSTARTUP变量,值为绝对路径的 tab.py,例如:

变量名:PYTHONSTARTUP

变量值:C:\Program Files (x86)\Python2\Lib\tab.py

注:不做这步的话,每次输入python进入交互界面后,需要手动import tab

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值