python curl 获取返回值_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是如果你的命令出錯的話,錯誤報告直接就刪除了,不會顯示在屏幕上??? 。
搞定!!
總結
以上是生活随笔為你收集整理的python curl 获取返回值_python获取系统命令的返回值 | curl in python的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 中varchar_MYSQL
- 下一篇: java 父子线程 调用链_ZipKin