如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

推荐学习

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

本文旨在讲解如何在Android平板或手机上搭建Python开发环境,帮助Python初学者有效利用碎片化时间进行学习,从而达到良好的学习效果。

对于大部分初学Python的人来说,由于工作、生活等因素常常无法进行连贯、系统的学习。初学者为了利用上下班通勤等碎片化时间进行学习,通常会在平板上观看学习视频并做记录。虽然这种方法很好,但效果还是不如边学边练来得好。

因此,你需要的是这个:

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

不多说,让我们开始吧!

一、Termux安装与配置

1. 系统要求

  • Android 7.0以上的平板或手机。这里建议使用兼顾了便携性和屏幕尺寸的8寸平板。
  • 2G以上可用空间。由于需要安装各种软件包,对存储空间的消耗还是比较大的。

2. Termux安装

在安装Termux前,需要了解一下什么是Termux。

Termux 是一款支持 Linux 环境的 Android 终端模拟器APP。你无需对手机进行root或额外设置即可使用。这款APP会在手机中自动安装一个最小化基本系统,并支持使用 APT 包管理工具安装软件。

目前Termux官网(https://termux.com/)建议使用F-Droid进行安装,不再支持通过Google Play进行安装。

  • 主程序Termux下载地址:

https://f-droid.org/repo/com.termux_106.apk

  • 美化工具Termux:Styling下载地址:

https://f-droid.org/repo/com.termux.styling_29.apk

3. Termux基本操作

  • 快捷键

Ctrl A -> 将光标移动到行首Ctrl E -> 将光标移动到行尾Ctrl C -> 中止当前进程Ctrl D -> 注销终端会话Ctrl K -> 从光标删除到行尾Ctrl U -> 从光标删除到行首Ctrl L -> 清除终端Ctrl Z -> 挂起(发送SIGTSTP到)当前进程音量加 E -> Esc键音量加 T -> Tab键音量加 1 -> F1(音量增加 2 → F2…以此类推)音量加 0 -> F10音量加 B -> Alt B,使用readline时返回一个单词音量加 F -> Alt F,使用readline时转发一个单词音量加 X -> Alt X音量加 W -> 向上箭头键音量加 A -> 向左箭头键音量加 S -> 向下箭头键音量加 D -> 向右箭头键音量加 L -> | (管道字符)音量加 H -> 〜(波浪号字符)音量加 U -> _ (下划线字符)音量加 P -> 上一页音量加 N -> 下一页音量加 . -> Ctrl (SIGQUIT)音量加 V -> 显示音量控制音量加 Q -> 切换显示的功能键视音量加 K -> 切换显示的功能键视图

4. 修改软件源

安装完Termux后,使用如下命令自动替换官方源为清华镜像源:

sed -i 's@^(deb.*stable main)$@#1ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/termux-packages-24 stable main@' $PREFIX/etc/apt/sources.listsed -i 's@^(deb.*games stable)$@#1ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/game-packages-24 games stable@' $PREFIX/etc/apt/sources.list.d/game.listsed -i 's@^(deb.*science stable)$@#1ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/science-packages-24 science stable@' $PREFIX/etc/apt/sources.list.d/science.listapt update && apt upgrade

5. 安装基本组件

在配置Python开发环境前,我们还需要使用如下命令安装一些基本软件包:

pkg install -y zsh curl wget build-essentialpkg install -y git python nodejs-lts perl ipythonpkg install -y neovim lazygit ranger fzf

二、终端配置

1. Shell配置

  • 安装oh-my-zsh

Shell的类型有很多种,Termux下默认使用的是bash,这里使用功能更强大的zsh来代替bash。为了让初学者更好地使用zsh,需要先安装高档大气上档次,狂拽炫酷吊炸天的oh-my-zsh

sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

安装过程中,会提示是否切换shell为zsh,输入回车Y即可。

此外,还需要安装zsh-autosuggestions插件,用于自动补全:

git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/plugins/zsh-autosuggestions

oh-my-zsh需要使用nanoneovim等终端编辑器修改.zshrc文件来进行配置,在plugins部分添加插件支持:

plugins=( git python colorize zsh-interactive-cd zsh-navigation-tools zsh-autosuggestions)

2. 主题美化

2.1 配色与字体

长按屏幕,点击More,选择Style可以选择配色和字体,推荐使用Neon配色和JetBrains Mono字体,也可以通过修改~/.termux/目录下的colors.propertiesfont.ttf文件进行自定义。

2.2 主题配置

接下来安装powerlevel10k的主题:

  • 安装

输入如下命令下载powerlevel10k:

git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k

修改.zshrc文件,将ZSH_THEME="robbyrussell"改为ZSH_THEME="powerlevel10k/powerlevel10k"

  • 配置

重新打开Termux,输入p10k configure进入powerlevel10k的配置界面。第一次会自动下载默认字体,安装后会自动退出,重新打开Termux即可。

可以根据配置向导的提示,定制适合自己风格的终端界面。

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

3. 启用vi模式(可选)

Termux命令行中修改已经输入的命令比较麻烦。通过开启vi模式,用户可以像在vi编辑器里一样进行操作。对于vi用户来说,进入这种模式后,编辑和修改命令就显得十分得心应手了。

使用nanoneovim等终端编辑器修改.zshrc文件来进行配置,在plugins部分添加vi-mode项,开启vi模式。在命令行状态下,按Esc键,即可进入vi模式的普通模式

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

不过在默认的vi模式存在按键bug,需要在.zshrc文件最后添加如下配置:

# Better searching in command modebindkey -M vicmd '?' history-incremental-search-backwardbindkey -M vicmd '/' history-incremental-search-forward# Beginning search with arrow keysbindkey "033[1~" beginning-of-linebindkey "033[4~" end-of-linebindkey '^[[3~' delete-charbindkey "^[OA" up-line-or-beginning-searchbindkey "^[OB" down-line-or-beginning-searchbindkey -M vicmd "k" up-line-or-beginning-searchbindkey -M vicmd "j" down-line-or-beginning-search

三、Python包安装与配置

1. 安装环境配置

# 配置pypi源pip install pip -Upip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple# 依赖项pip install wheelpip install setuptools --upgrade

2 Python包安装

  • 安装numpyscipy

# 添加第三方仓库curl -LO https://its-pointless.github.io/setup-pointless-repo.shbash setup-pointless-repo.sh# 从仓库安装numpy scipypkg install -y numpy scipy

  • 安装lxml

# 安装lxml的依赖项pkg install -y libxml2 libxslt# 安装lxmlpip install lxml

  • 安装pillow

# 安装pillow的依赖项pkg install -y libjpeg-turbo libtiff pkg install -y littlecms tk libwebp libsodium# 安装pillowpip install pillow

  • 安装matplotlib

# 安装matplotlib的依赖项pkg install -y freetype libpngpip install kiwisolver cycler pip install pyparsing python-dateutil# 安装matplotlibpip install matplotlib

  • 安装pandas

# 安装pandas的依赖项pip install -y pytz cython# 安装pandasexport CFLAGS="-Wno-deprecated-declarations -Wno-unreachable-code"pip install pandas

  • 安装jupyter

# 安装jupyter依赖项pkg install -y libzmq libcrypt pkg-config# 安装jupyter pip install jupyter

待安装完成,输入jupyter notebook启动,将地址复制到浏览器中即可打开Jupyter。

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

四、IPython和NeoVim配置

对于希望在终端下进行使用的同学,推荐IPython NeoVim组合。

1. IPython配置

  • 安装IPython

# 安装yapfpip install yapf# 安装Pygmentspip install pygments# 安装ipythonpip install ipython

  • 创建配置文件

使用ipython profile create命令在~/.ipython/profile_default/目录下的创建ipython_config.py配置文件。

  • 修改配置文件

使用neovim、nano等终端编辑器修改~/.ipython/profile_default/目录下的ipython_config.py文件,添加如下配置:

# 配置终端颜色c.InteractiveShell.colors = 'Linux'c.TerminalInteractiveShell.autoformatter = 'yapf' # 配置高亮方案,可通过pygmentize -L styles浏览所有可选配置c.TerminalInteractiveShell.highlight_style = 'monokai' # 配置魔术命令�itor使用的编辑器c.TerminalInteractiveShell.editor = 'nvim'

2. NeoVim配置

在配置NeoVim前,需要安装pynvim插件,以扩展NeoVim对Python的支持。

pip install pynvim

  • 创建init.vim文件进行基本配置

在命令行下,通过nvim命令进入NeoVim编辑器,输入:e $MYVIMRC编辑NeoVim配置文件,使用:w进行保存,基本设置如下:

" 一般设置set nocompatible "关闭与vi的兼容模式set number "显示行号set nowrap "不自动折行set showmatch "显示匹配的括号set scrolloff=3 "距离顶部和底部3行"set encoding=utf-8 "编码set fenc=utf-8 "编码set fileencodings=utf-8set hlsearch "搜索高亮syntax on "语法高亮set tabstop=4 "tab宽度set shiftwidth=4 set smarttabset backspace=indent,eol,startset expandtab "tab替换为空格键set fileformat=unix "保存文件格式set splitbelowset cmdheight=2set completeopt=longest,menuset splitrightset foldmethod=indentset foldlevel=99" 设置空格为leader键let mapleader=" "

  • 使用vim-plug安装NeoVim插件

vim-plug是一款Vim插件管理工具,支持异步并行,可以快速安装、更新或卸载插件。可以通过如下命令进行安装,或手动下载plug.vim文件,复制到在~/.config/nvim/autoload文件夹中。

curl -fLo ~/.config/nvim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

使用vim-plug时,需要在init.vim中添加下列代码块。

" vim-plug插件管理call plug#begin('~/.config/nvim/plugged')Plug 'junegunn/vim-plug'call plug#end()

保存后,在普通模式下输入:so %使配置文件生效,再通过:PlugInstall进行安装。

  • 常用插件及设置

下面列举了一下常用插件和基本设置:

call plug#begin('~/.config/nvim/plugged')Plug 'junegunn/vim-plug'" git支持Plug 'tpope/vim-fugitive'" Python自动缩进插件Plug 'vim-scripts/indentpython.vim'" 项目管理工具Plug 'mhinz/vim-startify'" 快速对齐插件Plug 'junegunn/vim-easy-align'" 当前光标下的单词增加下划线Plug 'itchyny/vim-cursorword'" 快速选择插件Plug 'tpope/vim-surround'" 自定义代码片断Plug 'honza/vim-snippets'" 语法高亮支持Plug 'sheerun/vim-polyglot'" 主题、状态栏设置Plug 'haishanh/night-owl.vim'Plug 'vim-airline/vim-airline'Plug 'vim-airline/vim-airline-themes'Plug 'ryanoasis/vim-devicons'" coc扩展Plug 'neoclide/coc.nvim', {'branch': 'release'}" fzf模糊查找Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }Plug 'junegunn/fzf.vim'" whichkey快捷菜单Plug 'liuchengxu/vim-which-key" 浮动窗口支持Plug 'voldikss/vim-floaterm'" ranger文件管理器支持Plug 'kevinhwang91/rnvimr'call plug#end()" 启用标签栏let g:airline#extensions#tabline#enabled = 1" 支持图标字体let g:airline_powerline_fonts = 1" 设置状态栏主题let g:airline_theme='night_owl'" 设置主题set termguicolorslet &t_8f = "<Esc>[38;2;%lu;%lu;%lum"let &t_8b = "<Esc>[48;2;%lu;%lu;%lum"syntax enablecolorscheme night-owl

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

  • 安装、配置coc.nvim扩展

coc.nvim是一款支持扩展的插件,类似于油猴,可以通过安装扩展,以实现像Vscode一样使用NeoVim,下面列举了Python相关的coc扩展和配置:

" coc扩展let g:coc_global_extensions = [ 'coc-json', 'coc-pyright', 'coc-snippets', 'coc-xml', 'coc-explorer', 'coc-prettier', 'coc-highlight']" 使用tab键进行补全选择inoremap <silent><expr> <TAB> pumvisible() ? "<C-n>" : <SID>check_back_space() ? "<TAB>" : coc#refresh()inoremap <expr><S-TAB> pumvisible() ? "<C-p>" : "<C-h>"function! s:check_back_space() abort let col = col('.') - 1 return !col || getline('.')[col - 1] =~# 's'endfunction" 使用回车进行补全选择inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm() : "<C-g>u<CR><c-r>=coc#on_enter()<CR>"" Highlight the symbol and its references when holding the cursor.autocmd CursorHold * silent call CocActionAsync('highlight')" Add `:Format` command to format current buffer.command! -nargs=0 Format :call CocAction('format')" Add `:Fold` command to fold current buffer.command! -nargs=? Fold :call CocAction('fold', <f-args>)" Add `:OR` command for organize imports of the current buffer.command! -nargs=0 OR :call CocAction('runCommand', 'editor.action.organizeImport')" 添加状态栏显示支持set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}" 启用Prettier进行文件自动格式化command! -nargs=0 Prettier :CocCommand prettier.formatFilelet g:prettier#autoformat = 1" 设置Coc Searchnnoremap <leader>? :CocSearch <C-R>=expand("<cword>")<CR><CR>

此外,coc扩展可以通过在~/.config/nvim/文件夹中创建coc-settings.json文件来进行配置:

{ "python.defaultInterpreterPath": "/data/data/com.termux/files/usr/bin/python", "python.pythonPath": "/data/data/com.termux/files/usr/bin/python", "python.linting.pylintEnable":true, "python.formatting.provider": "yapf", "python.formatting.yapfArgs": [ "--style", "{SPACES_AROUND_POWER_OPERATOR: True, SPACES_BEFORE_COMMENT: 1}" ], "explorer.width": 38, "explorer.quitOnOpen": true, "explorer.sources": [ { "name": "buffer", "expand": false }, { "name": "file", "expand": true } ], "explorer.file.column.indent.indentLine": true, "explorer.file.showHiddenFiles": true, "explorer.icon.enableNerdfont": true, "explorer.keyMappingMode": "none", "explorer.buffer.showHiddenBuffers": false, "explorer.keyMappings.global": { "o": ["wait", "expanded?", "collapse", "expand"], "<cr>": ["wait", "expandable?", "cd", "open"], "?": "help", "q": "quit" }, "coc.preferences.formatOnSaveFiletypes": ["*"], "prettier.printWidth": 100, "prettier.eslintIntegration": true, "prettier.disableLanguages": [], "prettier.formatterPriority": 1, "prettier.useTabs": true, "prettier.trailingComma": "all", "prettier.singleQuote": false, "prettier.tabWidth": 4}

  • 配置vim-which-key

vim-which-key是一款快捷键映射插件,可以通过简单的设置进行快捷键自定义功能的实现。下面列举了vim-which-key的简单设置:

" 将空格设置为whichkeyleader键nnoremap <silent> <leader> :WhichKey '<Space>'<CR>" whichkey基本配置let g:which_key_timeout = 100let g:which_key_display_names = {'<CR>': '↵', '<TAB>': '⇆'}let g:which_key_map = {}let g:which_key_sep = '→'let g:which_key_use_floating_win = 0let g:which_key_max_size = 0" 呼出whichkey时隐藏状态栏autocmd! FileType which_keyautocmd FileType which_key set laststatus=0 noshowmode noruler | autocmd BufLeave <buffer> set laststatus=2 noshowmode ruler" 自定义whichkeylet g:which_key_map['?'] = 'search word'let g:which_key_map['/'] = [ ':call Comment()' , 'comment' ]let g:which_key_map['.'] = [ ':e $MYVIMRC' , 'open init' ]let g:which_key_map[';'] = [ ':Commands' , 'commands' ]let g:which_key_map['e'] = [ ':CocCommand explorer --toggle --sources=file ' , 'explorer' ]let g:which_key_map['n'] = [ ':let @/ = ""' , 'no highlight' ]let g:which_key_map['q'] = [ '<Plug>(coc-fix-current)' , 'quickfix' ]let g:which_key_map['u'] = [ ':UndotreeToggle' , 'undo tree']let g:which_key_map['t'] = [':FloatermNew --wintype=normal --height=6' , 'terminal']let g:which_key_map['r'] = [ ':FloatermNew ranger' , 'ranger']let g:which_key_map['f'] = [':FloatermNew fzf' , 'fzf']let g:which_key_map['g'] = [':FloatermNew lazygit' , 'git']let g:which_key_map['p'] = [':FloatermNew python' , 'python']call which_key#register('<Space>', "g:which_key_map")

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

  • 在NeoVim中运行Python脚本

可以通过在NeoVim中添加自定义功能,从而在编写时运行当前Python脚本。

"在普通模式下,按r来运行Python脚本noremap r :call RunPython()<CR> func! RunPython() exec "w" if &filetype == 'python' exec "!time python %" endifendfunc

如何在你的Android手机上配置 Python 环境?(安卓手机python开发环境)

五、结语

本文主要分享了一下在Android平板上配置Python学习环境的经验,相关配置文件请参见以下链接:https://gitee.com/knightz1224/termux_config,谢谢大家支持!

作者:Python中文社区

原文链接:https://mp.weixin.qq.com/s/v0_NkTOxmvUuaVvt5EYBVA

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

(0)
上一篇 2023年4月22日 上午9:02
下一篇 2023年4月22日 上午9:18

相关推荐