Skip to content

Instantly share code, notes, and snippets.

@SahbiOuali13
Last active August 21, 2022 09:23
Show Gist options
  • Save SahbiOuali13/e4c29c0d3982694ea4bd9fd4807432e8 to your computer and use it in GitHub Desktop.
Save SahbiOuali13/e4c29c0d3982694ea4bd9fd4807432e8 to your computer and use it in GitHub Desktop.
  • This is a command-line tool that you can call to start a project. It’ll take care of creating a README.md file and a .gitignore file, and then it’ll run a few commands to create a virtual environment, initialize a git repository, and perform your first commit.
  • It’s even cross-platform, opting to use pathlib to create the files and folders, which abstracts away the operating system differences.
from pathlib import Path
from argparse import ArgumentParser
import subprocess


def create_new_project(name):
    project_folder = Path.cwd().absolute() / name
    project_folder.mkdir()
    (project_folder / 'README.md').touch()
    with open(project_folder / '.gitignore', mode='w') as f:
        f.write('\n'.join(['venv', '__pycache__']))
        
    commands = [
        [
            'python',
            '-m',
            'venv',
            f'{project_folder}/ venv', 
        ],
        ['git', '-C', project_folder, 'init'],
        ['git', '-C', project_folder, 'add', '.'],
        ['git', '-C', project_folder, 'commit', '-m', 'initial commit'],
    ]
    for command in commands:
        try:
            subprocess.run(command, check=True, timeout=60)
        except FileNotFoundError as exc:
            print(f"Command {command} failed because the process"
                  f"could not be found.\n{exc}")
        except subprocess.CalledProcessError as exc:
            print(
                f"Command {command} failed because the process "
                f"did not return a successful return code.\n{exc}"
            )
        except subprocess.TimeoutExpired as exc:
            print(f"Command {command} timed out.\n {exc}")
            
if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("project_name", type=str)
    args = parser.parse_args()
    create_new_project(args.project_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment