Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Output to a zip
#1
I tried to do some searching, however I was unable to find how to do this. I wanted to see if anyone has any suggestions on this. I am trying to get the output of this program to end up in a zip file. Thank you

import base64
from github import Github
from pprint import pprint
from shutil import make_archive
from zipfile import ZipFile
file = "github-repo"  # zip file name
directory = "output"

# Github username
name = input()
username = name
# pygithub object
g = Github()
# get that user by username
user = g.get_user(username)

for repo in user.get_repos():
    print(repo)
make_archive(file, "zip", directory)  # zipping the directory
Yoriz write Mar-10-2022, 06:27 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
Interesting task. I did it because it could be useful:

import shutil
from pathlib import Path
from subprocess import run, DEVNULL
from github import Github


OUTPUT_DIR = Path("output")
username = input("Please enter your GitHub username: ")

if not username.strip():
    raise RuntimeError("An empty username is not allowed")

git = Github()
git_user = git.get_user(username)

# The method Github.get_user returns Repos
# You can access the clone_url for example
# https://pygithub.readthedocs.io/en/latest/github_objects/Repository.html#github.Repository.Repository.clone_url
for repo in git_user.get_repos():
    # creating directory structure: output/username/repo.name
    repo_dir = Path(OUTPUT_DIR, username, repo.name)
    # creating directory structure: output/username/repo.name
    # ignore existing directories, otherwise it fails if the directory
    # exists already
    repo_dir.mkdir(parents=True, exist_ok=True)
    print("Cloning", repo.name)
    # using git command to clone the repos
    # redirecting outputs to devnull
    # no exception handling, it may fail and you don't see why
    run(["git", "clone", repo.clone_url, repo_dir], stderr=DEVNULL, stdout=DEVNULL)


print("Creating ZIP archive")
archive = shutil.make_archive(
    OUTPUT_DIR / username, "zip", root_dir=OUTPUT_DIR / username
)
print(f"Archive {archive} has been created")
print("Deleting old files")
shutil.rmtree(OUTPUT_DIR / username)
The function shutil.make_archive is hard to use. I needed 4 tries to get the correct directory structure inside the zip file.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank you. That was well noted and works very well. That will be a huge help moving forward with other projects. Thanks again
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020