【问题标题】:ipython notebook argparse erroripython笔记本argparse错误
【发布时间】: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


【解决方案1】:

就像错误消息所说的那样,你给它的参数太少了。您可能可以添加

import sys
sys.argv = ['scriptname.py', 'argument1', ...]

在脚本的顶部,使其在 Jupyter 中运行。使用命令行版本中的任何参数。

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2015-05-23
    • 2014-04-13
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    相关资源
    最近更新 更多