我有一个脚本,我试图创建一个类来封装用户名和pswd用于GitHub身份验证并构建存储库对象。
我正在创建类,因为我想在另一个脚本中使用凭据和用户变量(来构建repo)。
我试图将值返回给函数,但是我收到一条错误消息。我得到的两个错误消息是attributeerror和未定义的变量。
我的语法不对,但我无法弄清楚我在哪里弄错了。
我尝试了不同的变化,仍然无法让它发挥作用。
我想我需要将函数的结果返回到gh
和user
变量,然后使用函数:result = myobjectx.function().repository(myobjectx.function().user, repo).pull_requests('open')
。我按照这里的教程:http://www.learnpython.org/en/Classes_and_Objects
我已经尝试过这种变化,它仍然无法正常工作,我认为这是因为所有这一切都会再次提示输入凭据并且它没有看到用户变量??
#! /usr/bin/python
import os
import github3
from github3 import login, GitHub, authorize
from getpass import getuser, getpass
import requests
import csv
import configparser
import sys
import datetime
import codecs
sys.__stdout__ = codecs.getwriter('utf8')(sys.stdout)
# Class to authenticate to GitHub
class GitAuth:
def function(self):
try:
import readline
except ImportError:
pass
try:
user = input('GitHub username: ')
except KeyboardInterrupt:
user = getuser()
password = getpass('GitHub token for {0}: '.format(user))
gh = login(user, password)
myobjectx = GitAuth()
myobjectx.function()
# read the contents of the config file to pull in the repo name
config = configparser.ConfigParser()
config.read('repo.ini')
repo = config.get('repos', 'repo1')
result = myobjectx.gh.repository(user, repo).pull_requests('open')
def list_all_prs():
# open csv file and create header rows
with open('c:\\pull.csv', 'w+', newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Id', 'Login', 'Title', 'Commits', 'Changed Files'])
# iterate through repo for pull requests based on criteria and output to csv file
for pr in result:
data = pr.as_dict()
changes = (mybojectx.gh.repository(myobjectx.user, repo).pull_request(data['number'])).as_dict()
# keep print to console statement for testing purposes
# print(changes['id'], changes['user']['login'], changes['title'], changes['commits'], changes['changed_files'])
with open('c:\\pull.csv','a+',newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow([changes['id'], changes['user']['login'], changes['title'], changes['commits'],
changes['changed_files']])
list_all_prs()
错误讯息:
Traceback (most recent call last):
File "authent_test.py", line 48, in <module>
result = myobjectx.gh.repository(user, repo).pull_requests('open')
AttributeError: 'GitAuth' object has no attribute 'gh'
repo.ini:
[repos]
repo1 = some-repo
答案 0 :(得分:0)
第一个问题是gh
是在方法中定义的,而不是GitAuth的属性。
第二个问题是用户是在类中定义的,但在此处调用:
result = myobjectx.gh.repository(user, repo).pull_requests('open')
因此user
将在此时未定义。
class GitAuth:
gh = None
def function(self):
try:
user = input('GitHub username: ')
except KeyboardInterrupt:
user = getuser()
password = getpass('GitHub token for {0}: '.format(user))
self.gh = login(user, password)
return user
myobjectx = GitAuth()
user = myobjectx.function()
我也不明白为什么这块代码存在。它似乎没有做任何事情:
try:
import readline
except ImportError:
pass