【发布时间】:2018-12-16 02:04:06
【问题描述】:
如果我从命令行运行此代码,它可以正常工作。
import argparse
import sys
from googleapiclient import sample_tools
from pprint import pprint
def execute_request(service, property_uri, request):
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.
"""
return service.searchanalytics().query(
siteUrl=property_uri, body=request).execute()
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('property_uri', type=str,
help=('Site or app URI to query data for (including '
'trailing slash).'),
action='store_true')
argparser.add_argument('start_date', type=str,
help=('Start date of the requested date range in '
'YYYY-MM-DD format.'),
action='store_true')
argparser.add_argument('end_date', type=str,
help=('End date of the requested date range in '
'YYYY-MM-DD format.'),
action='store_true')
service, flags = sample_tools.init(
sys.argv, 'webmasters', 'v3', __doc__, 'client_secrets.json', parents=[argparser],
scope='https://www.googleapis.com/auth/webmasters.readonly')
# First run a query to learn which dates we have data for. You should always
# check which days in a date range have data before running your main query.
# This query shows data for the entire range, grouped and sorted by day,
# descending; any days without data will be missing from the results.
request = {
'startDate': flags.start_date,
'endDate': flags.end_date,
'dimensions': ['date']
}
response = execute_request(service, flags.property_uri, request)
pprint(response)
如果我从 ipython notebook 运行它,我会收到此错误:
ArgumentParser(prog='-c', usage=None, description=None, version=None, 格式化程序_class=, conflict_handler='error', add_help=False)
用法:-c [-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}] property_uri start_date end_date -c: 错误:参数太少
发生异常,使用 %tb 查看完整的回溯。
【问题讨论】:
-
您究竟是如何从命令行调用它的?你必须传递任何参数吗?
-
看看
sys.argv。错误用法看起来是由 jupyter 服务器产生的,而不是你的解析器。以前有人问过这个问题,我认为您不能在笔记本中进行命令行输入
标签: python python-3.x python-2.7 jupyter-notebook argparse