shell命令行执行python

每个脚本都有自己的擅长。

有次实现一个work,使用了shell,php,python看着文件种类多,不方便交接,看着也比较麻烦

减少文件种类数,也是很有必要的。

遇到的场景:shell程序需要从json中获取信息,继续处理。

文件, json.txt

{
    "name": "中国",
    "province": [{
        "name": "黑龙江",
        "cities": {
            "city": ["哈尔滨", "大庆"]
        }   
    }, {
        "name": "广东",
        "cities": {
            "city": ["广州", "深圳", "珠海"]
        }   
    }   
]
}

 可以在shell中直接调用python(注意load 与 loads的区别)

par@ubuntu:~/Desktop/test$ cat json.txt  | /usr/bin/python2.7 -c "import json; import sys; obj=json.load(sys.stdin); print obj['province'][1]['name'].encode('utf-8')"
广东
par@ubuntu:~/Desktop/test$ cat json.txt  | /usr/bin/python2.7 -c "import json; import sys; obj=json.load(sys.stdin); print obj['province'][1]['cities']['city'][1].encode('utf-8')"
深圳

其他链接: 

http://www.cnblogs.com/xudong-bupt/p/6218140.html

http://www.cnblogs.com/xudong-bupt/p/7291645.html

猜你喜欢

转载自www.cnblogs.com/xudong-bupt/p/9091582.html