Python command line 交互式框架

Python作为一种脚本语言,作为Perl的对手,在操作文件系统上面很有一套, 由于语言的推广,在web方面也出现了很多Python的框架,最有名的莫过于Django了,其实不太熟悉Django,但是近些年来Python在web方面没有太多的进展,反而back end javascript,例如nodejs的崛起,带动了javascript作为一个后端语言风潮,和以前的PHP,以及基于Java的J2ee, SpringMVC(曾经占有40%的web框架)竞争,个人觉得Python并不占优势。

Python需要找到自己的发展方向,无疑Shellscript作为linux娘胎里带来的语言,其蹩脚性显而易见,而Perl is ugly, everyone knows。所以python可以在Command line这条路上多走一些。

Prerequisite, I'm newbie in Python, so I just to share my learning python feelings. So Let's start.

Python and Pip

我是用maven用习惯了,所以没有build工具,以及作为3rd party包查找工具,我肯定要找一个,python肯定要提供一个,我第一步找到的是Pip,easy_install好像也可以但是重复了,我就熟悉了pip就够用了。pip的安装比较简单,执行python的一个远程get.pip.py的脚本就可以(这个方式显得有些不专业不得不说,而且没有和linux apt-get, Mac brew等等结合,显得有些low).而且,pip在开发中也不是必须的,这点让人有些沮丧,说明在开发大型项目的时候,python的标准化,还没有十分完备(个人意见)。

Run pip list will get you have already install python packages. sys.path you'll get the directory which python 3rd party packages location.

说起来,npm和bower这种安装工具提供本地安装,但是pip没有,是让人沮丧的,npm安装默认是本地,如果全局要加-g。

npm install -g bower

Python command line framework

说到今天的主题了,一直以来,我需要一个交互式的命令行程序,动态的申请虚拟机,删除虚拟机,安装一些软件等等,我希望都通过命令行来实现,而不是通过制作一个web端(以前,我一直是怎么做的)。所以我找到了python,找到了一些不错的,激动人心的python框架。
http://docs.python-guide.org/en/latest/scenarios/cli/
这篇文章中提到了几个。

Clint

没有好的文档,确实,这点比较致命,而且没法知道框架的全貌,不过几个功能还是不错的。https://github.com/kennethreitz/clint Github地址,因为是开发中,所以不完善是必须的,可以理解了。

  • 可以打印color,有前置的提示符
from clint.textui import puts, indent, colored

puts(colored.red('this is a text'))

with indent(4,">>> "):
        puts(colored.yellow("hello?"))

puts(colored.green('this is the end'))

  • 处理输入参数
from clint import arguments
args = arguments.Args()
print args.get(0)

Run python test.py 123 will print 123.

  • 处理输入流
from clint import piped_in
if __name__ == '__main__':
        in_data = piped_in()
        print in_data

Run python test.py < 1.txt will print 1.txt content.

  • 进度条打印
from time import sleep
from random import random
from clint.textui import progress

for i in progress.bar(range(100)):
        sleep(random()*0.2)

  • 提示框
from clint.textui import prompt,puts,colored,validators
name = prompt.query("What's your name?")
puts(name)
language = prompt.query("Your favorite tool (optional)?", validators=[])
puts(language)

Click

http://click.pocoo.org/3/ 更成熟的工具,研究一些高级功能。
格式化打印?
循环的询问?
……

posted @ 2015-02-04 11:56  一途  阅读(6621)  评论(0编辑  收藏  举报