Sobrescribir Argparse de la API de Google Drive v3 en Python
Estoy tratando de usar la API de Google Drive (v3) con Python para obtener y cargar archivos en mi cuenta de Google Drive.
Usé esta guía para configurar mi autenticación:https://developers.google.com/drive/v3/web/quickstart/python
Pero para mi programa, me gustaría tomar la entrada de la línea de comandos para nombre de usuario, nombre de archivo y nombre_archivo_salida. Modifiqué el código de Google Docs e hice lo siguiente:
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
El problema es que en el método get_credentials, hay una línea que dice:
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
Sin embargo, el método run_flow utiliza un argparser diferente que google escribió (ver:http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html)
Entonces, cada vez que ejecuto este script con mis propias entradas con nombre de usuario, nombre de archivo, etc., recibo un error que dice "Argumentos no reconocidos".
¿Cómo hago para que mi argparser sobrescriba el que está en run_flow?
EDITAR:
Alguien sugirió usar parse_known_args ().
Bueno, modifiqué mi código para analizar diciendo args, flags = parser.parse_known_args () porque de esa manera, cualquier error. las entradas irían a banderas.
La idea es que si ejecuto el script y le doy mis 3 args, debería convertirlos en "args".
Pero el problema con esto nuevamente es que más tarde cuando llamo al método run_flow en get_credentials, arroja un error que dice:
Uso: name.py [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG, INFO, WARNING, ERROR, CRITICAL}] Argumentos no reconocidos: -u shishy -f fname -d nombre_aleatorio
Creo que todavía está pasando mi entrada de línea de comando al método get_info y el analizador no tiene idea de qué hacer con él ...