A memorandum for those who use Python very occasionally [API access JSON and XML parsing argument parsing shell command regular expression]

I want to use it when I want to access the API easily, so I will leave it as a memo Since I use Python only occasionally, I think there are quite a few things to dig into, so if you have any mistakes or should do this, thank you.

JSON access with API

# -*- coding:utf-8 -*-

import json, requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = json.loads(resp.text)
#To complement in the IDE
if 0: assert isinstance(data, dict)
print data["status"]

XML access with API

import requests, xml.etree.ElementTree as etree

url = 'http://maps.googleapis.com/maps/api/directions/xml'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
text = resp.text.encode('utf-8')

data = etree.fromstring(text)
#To complement in the IDE
if 0: assert isinstance(data, etree.Element)
print data.find("status").text

Argument parsing

import argparse
parser = argparse.ArgumentParser(description='Sample command')
parser.add_argument('arg1', help='Application package name(s)')
parser.add_argument('--a', dest="a", help='Application package name(s)')

args = parser.parse_args()
arg1 = args.arg1
print arg1
a = args.a
print a

input

python test.py example --a b

output

example
b

Call the command line and extract from the string with a regular expression

import subprocess
from subprocess import PIPE
import re

system_dump_command = ["adb", "shell", "dumpsys", "activity", "activities"]
system_dump = subprocess.Popen(system_dump_command, stdout=PIPE, stderr=PIPE).communicate()[0]
running_package_name = re.search(".*TaskRecord.*A[= ]([^^}]*)",system_dump).group(1)
print running_package_name

The following character string comes out from the command adb shell dumpsys activity activities

ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)
  Stack #0:
    Task id #1
    * TaskRecord{#1 A=com.android.launcher U=0 sz=1}
      numActivities=1 rootWasReset=false userId=0 mTaskType=1 numFullscreen=1 mOnTopOfHome=false
      affinity=com.android.launcher

With regular expression

com.android.launcher

Is being taken out.

Recommended Posts

A memorandum for those who use Python very occasionally [API access JSON and XML parsing argument parsing shell command regular expression]
[Short sentence] easygui for those who want to use a simple GUI with Python very easily
A memo for those who use Python in Visual Studio (me)
Tips for those who are wondering how to use is and == in Python