python - 从 python 中的 curl 命令获取输出。
问题描述
如何将 curl 命令的结果设置为变量,(所以在这个 IP 地址中。)
import subprocess; ip = subprocess.call("curl ident.me", shell=True)
120.12.12.12
ip returns "0"
解决方案
使用requests
模块比通过 shell 运行 curl更好
>>> import requests
>>> r = requests.get('http://ident.me')
>>> r.text
'137.221.143.78'
>>>
如果由于某种原因,您无法使用requests
模块,请尝试使用subprocess.check_output
>>> ip = subprocess.check_output("curl -s ident.me".split())
>>> ip
'137.221.143.78'
推荐阅读
- javascript - Jquery-日期转换问题
- c# - 统一生成对象
- javascript - 向浏览器输出响应
- mongodb - 使用 MongoEngineObjectType 使 ID 字段成为必需
- javascript - 从子组件更新父组件的对象数组的正确方法是什么?
- ios - iOS Swift 如何检测登录错误原因以向用户显示正确的错误警报
- node.js - 在 nodejs 中拆分和重建文件会通过某些格式更改其长度
- android - Android camera2 图像方向问题
- asp.net - 如何让命令 dotnet 恢复?
- terraform - terraform中的不同模块可以使用相同的vars文件吗