Argparse AttributeError:“命名空间”对象没有属性

2024-05-21 06:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道已经有几十篇关于这些错误的帖子了,但我似乎仍然无法理解我的错误。我正在使用Google Analytics Reporting API(v4)并结合从Googlethis site找到的脚本

所讨论的代码只是尝试初始化Google Analytics,并创建一个名称中包含脚本参数的csv文件,数据将进一步保存在代码中。在我添加创建文件的行(var basic_url…)之前,一切都很顺利

代码的运行方式为:filename.py 'website_url.com' 'start_date' 'end_date'

import argparse
import csv
import sys

from apiclient.discovery import build

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools


from googleapiclient import sample_tools
from googleapiclient import errors

# 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).'))
argparser.add_argument('start_date', type=str,
                       help=('Start date of the requested date range in '
                             'YYYY-MM-DD format.'))
argparser.add_argument('end_date', type=str,
                       help=('End date of the requested date range in '
                             'YYYY-MM-DD format.'))

SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
# Path to client_secrets.json file for initializing google analytics object
CLIENT_SECRETS_PATH = 'analytics_client_secrets.json' 
VIEW_ID = 'XXXXXXX'


def initialize_analyticsreporting(argv,):
  """Initializes the analyticsreporting service object.

  Returns:
    analytics an authorized analyticsreporting service object.
  """
  # Parse command-line arguments.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser])
  flags = parser.parse_args([])

  # Set up a Flow object to be used if we need to authenticate.
  flow = client.flow_from_clientsecrets(
      CLIENT_SECRETS_PATH, scope=SCOPES,
      message=tools.message_if_missing(CLIENT_SECRETS_PATH))

  # Prepare credentials, and authorize HTTP object with them.
  # If the credentials don't exist or are invalid run through the native client
  # flow. The Storage object will ensure that if successful the good
  # credentials will get written back to a file.
  storage = file.Storage('analyticsreporting.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow, storage, flags)
  http = credentials.authorize(http=httplib2.Http())

  # Build the service object.
  analytics = build('analyticsreporting', 'v4', http=http)
  
  basic_url = flags.property_uri
  basic_url = basic_url.replace("://","_")
  basic_url =basic_url.replace(".","-")
  
  # Create blank csv file
  f= open("./Landingpage_analytics_"+flags.start_date+"_"+flags.end_date+"_"+basic_url+".csv", 'wt')
  writer = csv.writer(f)
  writer.writerow( ('Landingpage', 'Sessions', 'Bounces', 'avg. Session Duration', 'avg. Pages/Session') )
  f.close()

  return analytics, flags

我特别困惑,因为我在同一个脚本中使用Google搜索控制台API,并使用以下行初始化变量flags,并且访问参数没有问题,例如flags.start_dateflags.property_uri

service, flags = sample_tools.init(
      argv, 'searchconsole', 'v1', __doc__, __file__, parents=[argparser],
      scope='https://www.googleapis.com/auth/webmasters.readonly')

以下是回溯:

Traceback (most recent call last):

  File "/Users/gabrielh/Documents/Python/EVE Python/Search/attempt3.py", line 483, in <module>
    main()

  File "/Users/gabrielh/Documents/Python/EVE Python/Search/attempt3.py", line 478, in main
    analytics, flags = initialize_analyticsreporting(sys.argv)

  File "/Users/gabrielh/Documents/Python/EVE Python/Search/attempt3.py", line 108, in initialize_analyticsreporting
    basic_url = flags.property_uri

AttributeError: 'Namespace' object has no attribute 'property_uri'

Tags: csvthefromimporturldateobjectbasic