Home > Software engineering >  Fetch a single word from an output in python?
Fetch a single word from an output in python?

Time:03-03

I need to fetch a single character from an output and put it in if statement.

I enter this

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"
}                                           

in this output i have to just check if Convergence is present in the org line.

How do i do that in python?

CodePudding user response:

You can do so with the requests library:

import requests


resp = requests.get("https://ipinfo.io")
if "Convergence" in resp.json().get("org", ""):
    print("yay")

note: This requires the installation of requests which is not in python standard library. It can be installed a few ways. One example is pip install requests, but here is the official installation guide

CodePudding user response:

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

Note that JSON is not inside any varible. So do this:

x = {Your JSON file HERE}

so check it like this:

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

CodePudding user response:

Solution which use solely elemnets of python's standard library

import json
import urllib.request
with urllib.request.urlopen('http://ipinfo.io') as f:
    data = json.load(f)
print('Convergence' in data['org'])

Disclaimer: this code assumes that you do always get as response Object which has some org.

CodePudding user response:

Using the requests module to GET the JSON response from that URL would be a better approach.

If however you insist on running curl you could do this:

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')

This is how you could do it using 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')
  • Related