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是若是你的命令出錯的話,錯誤報告直接就刪除了,不會顯示在屏幕上    。 java

    搞定!! python

相關文章
相關標籤/搜索