shi*_*shy 3 python argparse google-drive-api oauth2
我正在尝试使用带有Python的Google Drive API(v3)来获取文件并将其上传到我的Google云端硬盘帐户.
我使用本指南设置了我的身份验证:https://developers.google.com/drive/v3/web/quickstart/python
但是对于我的程序,我想对username,filename和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
Run Code Online (Sandbox Code Playgroud)
问题是在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 Code Online (Sandbox Code Playgroud)
run_flow方法虽然使用了谷歌写的不同的argparser(参见:http://oauth2client.readthedocs.io/en/latest/source/oauth2client.tools.html)
因此,每当我使用我自己的用户名,文件名等输入运行此脚本时,我会收到一条错误消息"无法识别的参数".
如何让我的argparser覆盖run_flow中的那个?
编辑:
有人建议使用parse_known_args().
好吧,我通过说args,flags = parser.parse_known_args()来修改我的代码来解析,因为这样,任何misc.输入将进入标志.
我的想法是,如果我运行脚本并给它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方法,并且解析器不知道如何处理它...
shi*_*shy 10
没关系,我明白了.hpaulj做对了.
在get_credentials()方法中,就在它调用run_flow()之前,我只需添加一行说:
flags=tools.argparser.parse_args(args=[])
credentials=tools.run_flow(flow, store, flags)
Run Code Online (Sandbox Code Playgroud)
当我用输入读取命令行时,我只是使用parser_known_flags()作为hpaulj建议!
谢谢,shishy