2014-09-30 2 views
2

Google의 Python API를 사용하여 감사 정보를 가져 오지만 argparse (API 액세스에 필요함) 및 자체 인수 (예 : 통과)에 대한 부모 그룹 인수를 가져올 수 없습니다. 날짜에) 함께 작업 할 수 있습니다.Google Admin API와 함께 Argparse 사용

코드 :

import pprint 
import sys 
import re 
import httplib2 
import json 
import collections 
import argparse 

from oauth2client import client 
from apiclient import sample_tools 
from apiclient import discovery 
from oauth2client.client import AccessTokenRefreshError 
from oauth2client.client import OAuth2WebServerFlow 
from oauth2client.file import Storage 
from oauth2client.tools import run 
from oauth2client import tools 

def main(argv): 
    # Parser for command-line arguments. 
    parser = argparse.ArgumentParser(
    description=__doc__, 
    formatter_class=argparse.RawDescriptionHelpFormatter, 
    parents=[tools.argparser]) 

    parser.add_argument("-d","--selected_date", help="Date (YYYY-mm-dd) to run user usage report", required=True) 

    args = parser.parse_args(argv[1:]) 
    print args 
    selected_date = args.selected_date 
    print selected_date 

    # Authenticate and construct service. 
    service, flags = sample_tools.init(
    argv, 'admin', 'reports_v1', __doc__, __file__, 
    scope='https://www.googleapis.com/auth/admin.reports.usage.readonly') 

    # If the Credentials don't exist or are invalid run through the native client 
    # flow. The Storage object will ensure that if successful the good 
    # Credentials will get written back to a file. 
    storage = Storage('admin.dat') 
    credentials = storage.get() 
    if not credentials or credentials.invalid: 
    credentials = run(FLOW, storage) 

그리고 명령 줄에서 실행 ...

> python user_report.py 
usage: user_report.py [-h] [--auth_host_name AUTH_HOST_NAME] 
        [--noauth_local_webserver] 
        [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] 
        [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] -d 
        SELECTED_DATE 
user_report.py: error: argument -d/--selected_date is required 

좋은 지금까지 ... 지금

> python user_report.py -d "2014-09-14" 
Namespace(auth_host_name='localhost', auth_host_port=[8080, 8090], logging_level='ERROR', noauth_local_webserver=False, selected_date='2014-09-14') 
usage: user_report.py [-h] [--auth_host_name AUTH_HOST_NAME] 
        [--noauth_local_webserver] 
        [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] 
        [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] 
user_report.py: error: unrecognized arguments: -d 2014-09-14 

그것은 나타납니다 인수를 추가 같은데 날짜 인수가 인식되지 않습니다. 어떤 도움을 많이 주시면 감사하겠습니다!

+0

당신은 또한 인수가 필요로 userkey을 포함해야 문제를 해결할? https://developers.google.com/resources/api-libraries/documentation/admin/reports_v1/python/latest/admin_reports_v1.userUsageReport.html pydocs에서 날짜가 더 이상 필요하지 않은 것 같습니다. – Emily

+0

나중에 모든 사용자의 이벤트를 가져 오는 "all"로 하드 코딩 된 app에 userKey를 추가합니다. 이 코드는 외부 인수를 전달하지 않을 때 작동합니다. 감사! – Alex

답변

1

IT는 무슨 일이 일어나고 다음과 같이 나에게 보이는 : 나는 tools.argparsersample_tools.init에 의해 운영되고 있음을 추측하고는 -d 인수에 대해 알고하지 않기 때문에 오류를 생산하고있어

args = parser.parse_args(argv[1:]) # runs fine 
print args       # produces the Namespace line 
selected_date = args.selected_date 
print selected_date     # where is this output? 

# Authenticate and construct service. 
service, flags = sample_tools.init(...) # is this producing the error? 

.

(저는이 API가 아니라 argparse에 익숙합니다).

+0

문제는 여기에 있습니다. Google에 따르면 Oauth2의 "상위"(tools.argparser 또는 tools.run_parser)를 내 파서에 전달하여 재정의 할 수 있어야합니다. 거의 작동하지만 체인의 뒷부분에서 -d 인수를 알지 못하는 것 같습니다. – Alex

3

나는 지금 일하고있다. sample_tools.init은 자신의 argparse 인스턴스를 (더 좋거나 나쁘게) 인스턴스화하고있다. Google API를 사용하면 부모 (사용자 정의 인수를 전달한 곳)에 전달할 수 있으며 모든 것이 작동합니다.

https://google-api-python-client.googlecode.com/hg/docs/epy/apiclient.sample_tools-pysrc.html

# Parser for command-line arguments 
parent = argparse.ArgumentParser(add_help=False) 
group = parent.add_argument_group('standard') 
parent.add_argument("-d","--selected_date", help="Date (YYYY-mm-dd) to run user usage report", required=True) 

flags = parser.parse_args(argv[1:]) 
print flags 
selected_date = flags.selected_date 
print selected_date 

# Authenticate and construct service. 
service, flags = sample_tools.init(
    argv, 'admin', 'reports_v1', __doc__, __file__, 
    scope='https://www.googleapis.com/auth/admin.reports.usage.readonly', parents=[parent]) 

여분의 인수 (부모를 통과하는) sample_tools.init하기는

+0

자신 만의 파서를 정의 할 수 있지만 직접 실행하지 마십시오. 그것은'sample_tools' 작업입니다. 'selected_date '를'flags'를 통해 다시 얻으십니까? – hpaulj

+0

@ hpaulj- 예, flags.selected_date로 액세스 할 수 있습니다. – Alex

관련 문제