python获取系统命令的返回值 | curl in python

项目背景:
     通过curl 命令 从服务器获取数组,tids,然后导入到Mysql 表中。
自己想的方案:
     shell命令不熟悉,另外python中的数据库等接口都已封装,所以想使用Python来做,利用Python调用shell命令。

curl --header "MLS: uid:xxxxx;ip:xxx.xx.xx" v.mls.com/gl/get_gl -d "pid=409&offset=0&limit=480"  #此为伪命令
  #返回值
  {"error_code":0,"data":{"tids":[1746922055,1746931247,1708272843],"usable_num":12082,"show_num":12464}}     # error_code=0 表示正常

Python中处理:
      +++++方案1: +++++++++
     #os.system ,最早了解到的执行系统命令的Python语句。
    
cmd = ''' curl --header "MLS: uid:xxxxx;ip:xxx.xx.xx" v.mls.com/gl/get_gl -d "pid=409&offset=0&limit=480"  '''  #此为伪命令
result = json.loads( os.system(cmd) )   
result['data']['tids']   
     # 异常  TypeError: expected string or buffer。可能是os.system()命令返回的类型不符,查了下Python文档"On Unix, the return value is the exit status of the process encoded in the format specified for wait()"  
     
     +++++方案2++++++++++      
     # commands.getoutput , 只返回执行结果,忽略返回值。
    
cmd = ''' curl --header "MLS: uid:xxxxx;ip:xxx.xx.xx" v.mls.com/gl/get_gl -d "pid=409&offset=0&limit=480"  '''  #此为伪命令
result = json.loads( commands.getoutput(cmd) )   
result['data']['tids']    
     #异常 ValueError: No JSON object could be decoded。
     打印出结果看一下,还是有一堆乱起八糟的东西!!!
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0{"error_code":0,"data":{"tids":[1746127431,1762265107,1763545785,168808712100  5378    0  5346  100    32  18924    113 --:--:-- --:--:-- --:--:-- 19092
83,1626151317,1717193707,1642206015,1701082599,1423118513,1474847025,1578211634,1743682339,1573758157,1671828749,1107839122,1671283222,1549615611,1626139235,1375268687,1664368093,1177596631],"usable_num":3914,"show_num":3914}}

     #加一个错误处理  
    
cmd = ''' curl --header "MLS: uid:xxxxx;ip:xxx.xx.xx" v.mls.com/gl/get_gl -d "pid=409&offset=0&limit=480"  2>/dev/null '''  #此为伪命令
result = json.loads( commands.getoutput(cmd) )   
result['data']['ties']

     #####  2>/dev/null是如果你的命令出错的话,错误报告直接就删除了,不会显示在屏幕上    。

    搞定!!


转载于:https://my.oschina.net/wangjiankui/blog/159848

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值