程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

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

发布于2019-08-30 14:38     阅读(1645)     评论(0)     点赞(19)     收藏(4)


项目背景:
     通过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是如果你的命令出错的话,错误报告直接就删除了,不会显示在屏幕上    。

    搞定!!




所属网站分类: 技术文章 > 博客

作者:23dh

链接:https://www.pythonheidong.com/blog/article/71290/26cccc4312a6d87d0aa4/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)