2016-10-06 9 views
1

Python과 함께 Google 드라이브 API (v3)를 사용하여 파일을 가져 와서 Google 드라이브 계정에 업로드하려고합니다. Google 드라이브 API v3 Python의 Argparse 덮어 쓰기

내가 설정 내 인증이 설명서에 사용 : https://developers.google.com/drive/v3/web/quickstart/python

을하지만 내 프로그램에, 나는 사용자 이름, 파일 이름 및 output_filename에 대한 커맨드 입력을하고 싶습니다. 나는 구글 문서 코드를 수정하고 다음을했다 :

from __future__ import print_function 
    import httplib2 
    import os 
    from sys import argv 
    from apiclient import discovery 
    from oauth2client import client 
    from oauth2client import tools 
    from oauth2client.file import Storage 
    from apiclient.http import MediaIoBaseDownload, MediaIoBaseUpload 
    import io 

    try: 
     import argparse 
     parser = argparse.ArgumentParser(description="I want your name, the file ID, and the folder you want to dump output to") 
     parser.add_argument('-u', '--username', help='User Name', required=True) 
     parser.add_argument('-f', '--filename', help='File Name', required=True) 
     parser.add_argument('-d', '--dirname', help = 'Directory Name', required=True) 
     flags = parser.parse_args() 

    except ImportError: 
     flags = None 

    SCOPES = 'https://www.googleapis.com/auth/drive' 
    CLIENT_SECRET_FILE = 'client_secret.json' 
    APPLICATION_NAME = 'Drive API Python Quickstart' 
    ...#rest of the code is from the Google Drive Documentation (see above) 

def get_credentials(): 
    """Gets valid user credentials from storage. 

    If nothing has been stored, or if the stored credentials are invalid, 
    the OAuth2 flow is completed to obtain the new credentials. 

    Returns: 
     Credentials, the obtained credential. 
    """ 

    home_dir = os.path.expanduser('~') 

    credential_dir = os.path.join(home_dir, '.credentials') 
    if not os.path.exists(credential_dir): 
     os.makedirs(credential_dir) 
    credential_path = os.path.join(credential_dir, 
            'drive-python-quickstart.json') 

    store = Storage(credential_path) 
    credentials = store.get() 
    #Credentials returns NONE 
    if not credentials or credentials.invalid: 
     flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) 
     flow.user_agent = APPLICATION_NAME 
     if args: 
      credentials = tools.run_flow(flow, store) 
     else: # Needed only for compatibility with Python 2.6 
      credentials = tools.run(flow, store) 
     print('Storing credentials to ' + credential_path) 

    print("check") 
    return credentials 

문제는 get_credentials 방법에,라는 한 줄 있다는 것입니다 :

if flags: 
    credentials = tools.run_flow(flow, store, flags) 
else: # Needed only for compatibility with Python 2.6 
    credentials = tools.run(flow, store) 

run_flow 방법은 비록 다른 argparser를 사용하여 그 google wrote (참조 : http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html)

그래서 나는이 스크립트를 사용자 이름, 파일 이름 등으로 내 자신의 입력으로 실행할 때마다 "인식 할 수없는 인수"라는 오류가 계속 발생합니다.

argparser를 run_flow에 덮어 쓰게하려면 어떻게합니까?

편집 :

누군가가 parse_known_args를 사용 제안().

음, args, flags = parser.parse_known_args()라고 말하는 것으로 구문 분석하도록 코드를 수정했습니다. 입력은 플래그로 들어갑니다.

내가 스크립트를 실행하고 3 개의 args를 주면 "args"로 가져와야한다는 생각입니다.

그러나이 문제는 나중에 다시 내가 get_credentials에 run_flow 메서드를 호출 할 때에, 그것은 말에서 오류가 발생한다는 것입니다 :

사용법 : name.py [--auth_host_name AUTH_HOST_NAME] [을 - noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT ...]] [--logging_level {DEBUG, INFO, WARNING, ERROR, CRITICAL}] 알 수없는 인자 : -u shishy -f FNAME -d random_name

내 커맨드 라인 입력을 여전히 통과하고 있다고 생각합니다. get_info 메쏘드와 파서 (parser)에 그걸로 무엇을 해야할지 모르겠다. ...

답변

1

나는 argparsegoogle api에 대해 다른 질문이 있었지만, 나는 후자를 사용하지 않았다.

파서는 독립적이며 덮어 쓸 수 없습니다. 그러나 그들 모두는 (디폴트로 어쨌든) sys.argv[1:]을 사용합니다. 따라서 코드가 다른 코드보다 먼저 실행되면 sys.argv을 편집하여 추가 문자열을 제거 할 수 있습니다. parse_known_args을 사용하면 다른 파서가 사용해야하는 인수와 인수를 구분할 수 있습니다.

종종 파서가 if __name__ 블록에서 호출됩니다. 그런 식으로 가져온 모듈은 구문 분석을하지 않고 스크립트로 사용한 모듈 만 해석합니다. 하지만 Google api가이 구분을하면 나는 안합니다.

+0

을 shishy(). argparse 부분은 함수 외부의 시작 부분에 있습니다. 나는이 게시물에 대해 실제로 생각하고 있었고 비슷한 것을 할 수있는 방법은 다음과 같습니다. https://stackoverflow.com/questions/26130741/using-argparse-with-google-admin-api 그게 바로 samples_tools.init()가 아니라는 것입니다. 새 버전에서. – shishy

+0

parse_known_args의 문제점은 get_info 메소드가이 오류의 원인이며, 이는 Google 메소드의 일부입니다. 커맨드 라인에 정보를 전달하면 구문 분석을 통해 "오우 와아가 내가 기대하는 바가 아니다"라고 말하려고합니다. – shishy

1

신경 쓰지 마, 알아 냈다. hpaulj 그것이 맞았 어.이 run_flow을()가 호출 직전 get_credentials에서

() 메소드는, 단순히 말하는 줄을 추가했다 :

flags=tools.argparser.parse_args(args=[]) 
credentials=tools.run_flow(flow, store, flags) 

그리고 내 입력을 가진 명령 줄을 읽기 시작 부분에

, I hpaulj가 제안한대로 parser_known_flags()를 사용했습니다!

덕분에, 자신의 막대기의 if__name__ 블록은 단지 주 초기화