首页 > 解决方案 > 从 python 中的 curl 命令获取输出。

问题描述

如何将 curl 命令的结果设置为变量,(所以在这个 IP 地址中。)

import subprocess; ip = subprocess.call("curl ident.me", shell=True)
120.12.12.12

ip returns "0" 

标签: pythoncurl

解决方案


使用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'

推荐阅读