0 991
从python的输出中获取一个单词_图一

python怎么判断一个字符串中是否包含某个字符。


我需要从远程的链接输出中获取单个字符

我输入这个

cloud_name = os.system(" curl ipinfo.io ")
print(cloud_name)

curl ipinfo.io                                                     127 ⨯
{
  "ip": "",
  "hostname": "broadband.actcorp.in",
  "city": "Bengaluru",
  "region": "Karnataka",
  "country": "IN",
  "loc": "",
  "org": "AS24309 Atria Convergence Technologies Pvt. Ltd. Broadband Internet Service Provider INDIA",
  "postal": "",
  "timezone": "Asia/Kolkata",
  "readme": "https://ipinfo.io/missingauth"
}          

在这个输出中,我只需要检查 org 行中是否存在 Convergence。

我如何在python中做到这一点?


Python 有自己的requests模块,这将使这更容易。

我不会那样说。requests不在标准库中。如果有的话,urllib.request是“Python 自己的”模块使这更容易。

os.system不允许您捕获输出。我同意您可能希望使用 Python 的本机 HTTP 支持来获取网页,而不是curl在此特定场景中使用,但如果您处于需要运行子进程并捕获其输出的情况,请使用该subprocess库。os.system文档也建议这样做。

标签答案


使用requests模块从该 URL 获取 JSON 响应将是一种更好的方法。

但是,如果您坚持运行curl您可以这样做:

import subprocess
import json

data = json.loads(subprocess.Popen('curl ipinfo.io', stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, shell=True).stdout.read())
if 'Convergence' in data['org']:
    print('Convergence found')
else:
    print('Not found')



这就是您可以使用requests的方式:


import requests

(r := requests.get('https://ipinfo.io')).raise_for_status()

if 'Convergence' in r.json()['org']:
    print('Convergence found')
else:
    print('Not found')


其他答案一

仅使用python标准库的元素的解决方案


import json
import urllib.request
with urllib.request.urlopen('http://ipinfo.io') as f:
    data = json.load(f)
print('Convergence' in data['org'])
免责声明:此代码假定您总是作为响应对象获得一些org.




其他答案二

您可以使用requests库执行此操作:



import requests


resp = requests.get("https://ipinfo.io")
if "Convergence" in resp.json().get("org", ""):
    print("yay")
注意:这需要安装requests它不在python标准库中。它可以通过几种方式安装。一个例子是pip install requests,但这里是官方安装指南



其他答案三


if 'Convergence' in variable_name['org']:
    print('Do Something')
请注意,JSON 不在任何变量中。所以这样做:



x = {Your JSON file HERE}
所以像这样检查它:



if 'Convergence' in x['org']:
    print('Do Something')



[分类] 猿说奇谈
[来源] https://stackoverflow.com/questions/71336521/fetch-a-single-word-from-an-output-in-python
[声明] 本站资源来自用户分享,如损害你的权益请联系客服QQ:120074275给予处理。