欢迎贵客来到小店。外头说Python玄乎,好似神仙法器;您得走进来瞧瞧,指不定就是些油盐柴米,就凑了个海陆空全席。
今儿讲讲小店发家的尖货 —— 胶水,俗称糨糊。
别看小店如今样样全活儿,廿年前可不这样。当时最有排场的,还是C/C++, Java这样的角儿,要么能通到硬件和核心去,要么就是个虚拟机,不怕崩;其次是科学家工程师们使的专门,比如Lisp,Fortran。Python当时甚是轻便,又与C是近亲,便与类似的Perl、Lua作伙,都被叫做胶水语言。
胶水能干啥呢,就是把大家伙儿的结果捯饬捯饬,黏在一起。
run_project 1 | python some.py | run_project 2 # 倒手就走标准输出
譬如有主顾拿来了个文件,里头是这么个内容:
[some_random_json]
{"message":"success","err_no":0,"data":[],"media_comment":null,"media_comment_total_num":0,"media_comment_has_more":false,"media_comment_enable":false,"total_number":0,"has_more":false,"offset":0,"fold_comment_count":0,"detail_no_comment":0,"ban_comment":false,"ban_comment_reason":"写评论","ban_comment_toast":"","ban_face":false,"ban_pic_comment":0,"ban_gif_suggest":0,"go_topic_detail":1,"show_add_forum":1,"stick_comments":[],"stick_total_number":0,"stick_has_more":false,"tab_info":{"current_tab_index":0,"tabs":["热度","时间"]},"group":{"user_id":2365802797089261,"user_name":"互联技术菜场","is_video":false,"content":"","content_rich_span":""},"repost_params":{"opt_id_type":0,"opt_id":0,"fw_id_type":4,"fw_id":6874995163844837892,"fw_user_id":2365802797089261,"title":"「Python杂货店」先讲那二十年的镇店之宝的“禅”机","cover_url":"http://p3-tt.bytecdn.cn/list/300x300/dfic-imagehandler/a3cd485e-4272-4850-9fc3-b03635516517","repost_type":211,"schema":""},"post_count":0,"stick_toast":1,"stable":true}
几百米长不带喘气的。客人就想知道个评论数。
咱小店就派上用场了,先照这料子调个胶:
[glue.py]
#!/usr/bin/env python
import json
import sys
import traceback
from pprint import pprint
tot_msg = ''
try:
for one_line_msg in sys.stdin:
tot_msg += one_line_msg.rstrip()
except Exception as e:
traceback.print_exc()
sys.exit(-1)
try:
json_msg = json.loads(tot_msg)
pprint(json_msg)
except Exception as e:
traceback.print_exc()
再往文件和查找中间一贴:
cat some_random_json | python glue.py | grep comment
现调胶水,总不是那么灵便,所以后来店里就储备了些常用的,加个-m的标记,就能找着:
cat some_random_json | python -m json.tool | grep comment
这标记后来成了小店的一道灵符。这是后话,在此先按下了。
当时小店备着不少材料,比如list的join,字符串的灵活操作,re模块,编解码模块。。。
就靠着轻便,上胶快,小店挣得了这编程闹市的一个位置。
至于后续,小店如何扩充起来,咱下回再聊。
高人!
/fad
这是实现了啥呀..?