12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

すごくたまーにPython使う人用の備忘録【APIアクセス JSONやXMLパース 引数のパース シェルコマンド 正規表現】

Posted at

手軽にAPIにアクセスしたい時とかに使いたいのでメモとして残しておきます
時々しかPython使っていないので突っ込みどころが結構あると思いますので、なにか間違いやこうしたほうがいいなどありましたらよろしくお願いします。

APIでJSONアクセス

# -*- 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)
# IDEで補完を効かせるため
if 0: assert isinstance(data, dict)
print data["status"]

APIでXMLアクセス

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)
# IDEで補完を効かせるため
if 0: assert isinstance(data, etree.Element)
print data.find("status").text

引数パース

import argparse
parser = argparse.ArgumentParser(description='サンプルコマンド')
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

入力

python test.py example --a b

出力

example
b

コマンドラインを呼び出して正規表現でその文字列の中から抽出

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

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

正規表現で

com.android.launcher

を取り出しています。

12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?