分享几个 Python 实现的实用命令行工具

文章目录

pyenv

pyenv 是一个使用简单的 Python 版本管理工具,可以让你简单的切换 Python 版本。Python2.x 在5年后将不在更新维护,所以是时候熟悉 Python3 了!

那么如何方便的即用 Python2 又可以在方便的切换到 Python3 呢?

上 pyenv 。当然,还有一个叫做 p 的工具也可以,不过比较之下我更喜欢 pyenv,pyenv 更强大些,但是 p 切换版本很方便。

安装:

curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

或者

brew install pyenv

在你的 shell rc 文件中添加:

export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

查看所有可用的命令:

pyenv commands

查看可以安装的 Python 版本:

pyenv install --list

查看当前可用的 Python 版本:

pyenv versions

安装和卸载其他版本的 Python:

pyenv install 3.4.0
pyenv rehash

pyenv uninstall 3.4.0

切换 Python 版本,默认版本为 system:

pyenv local 3.4.0   # 在当前目录改变python版本
pyenv local --unset # 取消改变
pyenv global 3.4.0  # 全局改变python版本
pyenv shell 3.4.0   # 改变当前shell的python版本

安装新版本的 Python 或者其他二进制包后都需要运行:

pyenv rehash

否则不会生效。

使用示例: 在 pyenv 中使用 virtualenv 部署 werkzueg 的测试 app :

# 将virtualenv安装在pypy中
pyenv local pypy-2.3.1
pyenv virtualenv venv_pypy
pyenv local venv_pypy
which python
pip install -Ur requirements.txt
pip install -U Gunicorn
pyenv rehash
which gunicorn
gunicorn -b :5000 -w 9 werkzeug.testapp:test_app

unp

unp 是一个草鸡好用的解压工具,支持格式:

  • ar AR Archives (*.a)
  • bz2 Bz2 Compressed Files (*.bz2)
  • tbz2 Bz2 Compressed Tarballs (*.tar.bz2)
  • gz Gzip Compressed Files (*.gz)
  • tgz Gzip Compressed Tarballs (*.tar.gz; *.tgz)
  • tar Uncompressed Tarballs (*.tar)
  • cab Windows Cabinet Archive (*.cab)
  • xz XZ Compressed Files (*.xz)
  • txz XZ Compressed Tarballs (*.tar.xz)
  • zip Zip Archives (*.zip; *.egg; *.whl; *.jar)

在 Linux 下解压文件只需

unp <FILENAME>

就能解压,无需再给一堆麻烦的参数。

安装 unp:

sudo pip install unp

cheat

好的,很多命令的参数你都记不住,你会 man 一下,但是是不是看起来效率很低,不具可读性呢?如果你这么觉得,那么 cheat 就是你需要的。

安装:

brew install cheat

或者

sudo pip install cheat

使用示例:

> cheat find
# To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG):
find . -iname "*.jpg"

# To find directories:
find . -type d

# To find files:
find . -type f

# To find files by octal permission:
find . -type f -perm 777

# To find files with setuid bit set:
find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l

# To find files with extension '.txt' and remove them:
find ./path/ -name '*.txt' -exec rm '{}' \;

# To find files with extension '.txt' and look for a string into them:
find ./path/ -name '*.txt' | xargs grep 'string'

# To find files with size bigger than 5 Mb and sort them by size:
find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z

# To find files bigger thank 2 MB and list them:
find . -type f -size +20000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'

# To find files modified more than 7 days ago and list file information
find . -type f -mtime +7d -ls

# To find symlinks owned by a user and list file information
find . -type l --user=username -ls

# To search for and delete empty directories
find . -type d -empty -exec rmdir {} \;

# To search for directories named build at a max depth of 2 directories
find . -maxdepth 2 -name build -type d

# To search all files who are not in .git directory
find . ! -iwholename '*.git*' -type f

# Find all files that have the same node (hard link) as MY_FILE_HERE
find . -type f -samefile MY_FILE_HERE 2>/dev/null

pipreqs/pigar

有没有觉得有时候 pip freeze > requirements.txt 里面有些乱七八糟的模块,可能是手贱安装的,也可能是安装了后来没有用到的,模块多了很难发现,那么要保持一个干净的 requirements 也可以很 easy 哦。

pipreqs 是一个根据你的项目的 import 来生成 requirements.txt 的工具。

安装:

pip install pipreqs

用法:

$ pipreqs /home/project/location
Successfully saved requirements file in /home/project/location/requirements.txt

pipreqs 我在使用过程中出现过生成的 requirements.txt 是空文件的情况,于是这里再推荐一个 pigar

安装:

pip install pigar

pigar 主要痛点是安装有一个小坑,装完执行命令时,可能会遇到这个报错:

ImportError: No module named '_sqlite3'

必须要依赖 sqlite3,如果你安装 python 前系统没有 sqlite3 那么你必须要先把 libsqlite3-dev 装上后再安装 python ,然后再 pip 安装才能正常使用。

ptpython

如果你喜欢 ipython ,那你一定会爱上 ptpython 。 ptpython 是一个比 ipython 更加高级的 Python REPL。

安装:

pip install ptpython

特性:

  • 可以选用vi或emacs模式 (默认emacs,ptpython --vi使用vi模式)
  • 语法高亮,语法检查
  • 自动补全 (tab/shift-tab,如果是vi模式可以C-n/C-p)
  • 多行编辑 (冒号后的代码会变成多行编辑,不会像ipython一样不好编辑)

安装:

pip install ptpython

如果你安装了 ipython,输入一把 ptipython 让你飞起来。

thefuck

thefuck 是一个改正你上一条错误命令的工具,当你输入了一个错误拼写的命令,这时直接输入fuck就可以运行你本来需要执行的正确命令。

使用示例:

我新建了一个分支,要 push 他,但是发现远程还没有,这么长的正确命令懒得复制,这时候你就可以 fuck 一下。

> git push
fatal: The current branch test has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin test
> fuck
git push --set-upstream origin test
Total 0 (delta 0), reused 0 (delta 0)
To git@github.com:axiaoxin/tests.git
* [new branch]      test -> test
Branch test set up to track remote branch test from origin.

安装:

pip install thefuck

然后在你的 .bashrc 中添加

alias fuck='eval $(thefuck $(fc -ln -1)); history -r'
# You can use whatever you want as an alias, like for Mondays:
alias FUCK='fuck'

zsh 粉在 .zshrc 中添加

alias fuck='eval $(thefuck $(fc -ln -1 | tail -n 1)); fc -R'

SimpleTornadoServer

python -m SimpleHTTPServer 传文件很巴适吧,但是 SimpleHTTPServer 不支持「续传」,和 wget 组合在糟糕的网络下传递一个稍大的文件总是会中途出错又重头再来,再来再错永远也下载不完。

那么,试试 python -m SimpleTornadoServer 吧,从此生活变得更加美好,你会有更多时间陪伴你的女朋友。

安装:

pip install SimpleTornadoServer

pythonpy

我们知道,在命令行可以直接执行某个 python 模块,还比如 json.tool 。

那么,我要直接执行 python 代码可以吗?我记不住 shell 语法我要直接用 python 好吗?

好的,pythonpy 带你飞。

安装:

pip install pythonpy

用法示例:

$ py '3 * 1.5'
4.5

$ py 'math.exp(1)'
2.71828182846

$ py 'random.random()'
0.103173957713

$ py 'range(3)'
0
1
2

$ py '[range(3)]'
[0, 1, 2]

$ py 'range(3)' | py -x 'int(x)*7'
0
7
14

$ py 'range(3)' | py -x 'x + ".txt"'
0.txt
1.txt
2.txt

$ py 'range(8)' | py -x 'x if int(x)%2 == 0 else None'
0
2
4
6

$ py 'range(3)' | py -l 'l[::-1]'
2
1
0

$ py 'range(3)' | py -l 'sum(int(x) for x in l)'
3

$ py 'range(17)' | py -l 'len(l)'
17

$ cat /usr/share/dict/words | py -x 'x[0].lower()' | py -l 'collections.Counter(l).most_common(5)'
('s', 11327)
('c', 9521)
('p', 7659)
('b', 6068)
('m', 5922)

$ py 'datetime.datetime.now?'
Help on built-in function now:

now(...)
    [tz] -> new datetime with tz's local day and time.

json2xls

json2xls 是一个根据 json 生成 excel 表格的工具

安装:

pip install json2xls

用法示例:

根据 json 字符串生成 excel

json2xls cmd_str_test.xls '{"a":"a", "b":"b"}'
json2xls cmd_str_test1.xls '[{"a":"a", "b":"b"},{"a":1, "b":2}]'

根据 json 文件生成 excel

json2xls cmd_list_test.xls "`cat list_data.json`"

根据每行一个 json 的文件生成 excel

json2xls cmd_line_test.xls line_data.json

根据返回 json 的 url 生成 excel

json2xls cmd_get_test.xls https://httpbin.org/get
json2xls cmd_post_test.xls https://httpbin.org/post -m post -d '"hello json2xls"' -h "{'X-Token': 'bolobolomi'}"

polysh

在没有集成日志的情况下,想同时查看多台机器的日志目前知道的最好用的方法是使用 polysh。它可以通过本地机器在远程同时执行命令,并显示结果。

polysh主页:https://guichaz.free.fr/polysh/

安装:

sudo pip install polysh

用法示例:

> polysh 'sh-talaris-crowd-loc-<1-8>'
ready (8)> date
sh-talaris-crowd-loc-1 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-3 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-5 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-6 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-4 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-8 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-7 : Tue Nov 24 15:16:53 CST 2015
sh-talaris-crowd-loc-2 : Tue Nov 24 15:16:53 CST 2015

所以要查看日志可以直接在本地执行

ready (8)> tail -f /var/log/ves/talaris-courier/courier.log | grep "push_location"

就能在本地集中打印日志。

watchmedo

在开发服务器类型的代码时,您可以在本地运行它来测试你的修改。不幸的是,每当您想尝试新版本的代码时,您必须停止服务器并重新启动它,这会减慢您的开发过程。

使用 watchmedo 可以在您更改代码时自动重新加载应用程序,然后使用 watchmedo auto-restart 来运行你的服务。

安装:

pip install 'watchdog[watchmedo]'

用法示例:

watchmedo auto-restart --pattern "*.py" --recursive --signal SIGTERM --signal SIGINT \
    python main.py -- --mode server

此示例假定服务器是在名为 app.py 的脚本中定义的。根据需要进行调整。

其他

顺便推荐一个叫做 csvkit 的命令行工具,命令行处理 csv 的大杀器。

还有 json 查询工具: jq ,命令行处理json的大杀器。

其他的还有类似 yapf,isort,autopep8 之类的也是值得推荐的,我多用于 vim 中,不在这里写了。


也可以看看


全国大流量卡免费领

19元月租ㆍ超值优惠ㆍ长期套餐ㆍ免费包邮ㆍ官方正品