Last active
January 2, 2022 13:33
-
-
Save michimani/b195b29f1c13edbc1df31542e14d2e6d to your computer and use it in GitHub Desktop.
Count GitHub stargazers. Execute `python3 count-github-stargazers.py github_user_name` . ⚠️ tested with only Python 3.7.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import sleep | |
from urllib.request import Request, urlopen | |
import argparse | |
import json | |
import traceback | |
GITHUB_REPOS_API = 'https://api.github.com/users/{user_name}/repos?per_page=100&page={page}' | |
PRINT_LINE = '{repo_name: <40}:{star_cnt: >6}' | |
p = argparse.ArgumentParser() | |
p.add_argument('user_name', help='GitHub user name') | |
args = p.parse_args() | |
def count_stargazers(repos_list): | |
total = 0 | |
for repo in repos_list: | |
if repo['stargazers_count'] > 0: | |
print(PRINT_LINE.format( | |
repo_name=repo['name'], star_cnt=repo['stargazers_count'])) | |
total += repo['stargazers_count'] | |
print('\n' + PRINT_LINE.format(repo_name='TOTAL', star_cnt=total)) | |
def get_repos_list(): | |
repos_list = [] | |
try: | |
page = 1 | |
repos_list_tmp = [] | |
while len(repos_list_tmp) > 0 or page == 1: | |
api = GITHUB_REPOS_API.format(user_name=args.user_name, page=page) | |
request = Request(api) | |
with urlopen(request) as res: | |
repos_list_tmp = json.load(res) | |
if len(repos_list_tmp) == 0: | |
break | |
repos_list += repos_list_tmp | |
page += 1 | |
if page > 10: | |
print('Abnormal number of attempts.') | |
break | |
sleep(1) | |
except: | |
print(traceback.format_exc()) | |
return repos_list | |
if __name__ == '__main__': | |
print('Count stargazers of {}\'s GitHub repositries...\n\n'.format(args.user_name)) | |
repos_list = get_repos_list() | |
count_stargazers(repos_list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment