Github with Python aka pyGithub module

Hi! This time we are gonna explore the module pyGithub to see if we can manage our repositories easily using Python.

Install pygithub

To install pyGithub, as usual, use pip:

pip install pyGithub

Access to your repositories

First of all, import the module like this

from github mport Github

then you have to give your credentials (put your username and the password):

g = Github("username","password")

Now, throug the ‘g’ object (istance of Github) you can have access to the repositories.

Get informations about yourself

You can have your username and your login name like this:

user = g.get_user()
print(user.name)
print(user.login)

Listing your repositories

To get the list of repositories do this:

repos = g.get_user().get_repos()
for repo in repos:
 print(repo.name)

Get a specific repo

To get a specific repo:

# use the name of your repository instead of "formazione...."
repo = g.get_user().get_repo("formazione.github.io")

# Output
# >>> repo
# >>> 'formazione.github.io'

Get all the files in a repo

contents = repo.get_contents("")
for c in contents:
 print(c.path)

# you will get all your files list

Get the stars…

To get the stars of a repo:

repo.stargazers_count

Get a specific content

To get a specific content

content = repo.get_contents("index.html")

Create a new file in the repo

To create a new file in the repo:

repo.create_file("text.txt","created a text file", "This is the content of the file")
# this will go in the master... to use a brach add branch='...'

Update the file you created

To update the file you created:

contents = repo.get_contents("text.txt")
repo.update_file(contents.path, "adding stuffs", "This is the new content of the file text.txt", contents.sha)

The live coding video

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.