|
| 1 | +""" |
| 2 | +Uses `subprocess` to creates a Python project, complete with a virtual |
| 3 | +environment and initialized Git repository. |
| 4 | +
|
| 5 | +Must have Git installed on the system with the `git` command available. |
| 6 | +
|
| 7 | +If your Python command is `python3`, change the `PYTHON_COMMAND` variable. |
| 8 | +""" |
| 9 | + |
| 10 | +from argparse import ArgumentParser |
| 11 | +from pathlib import Path |
| 12 | +import subprocess |
| 13 | + |
| 14 | +PYTHON_COMMAND = "python" |
| 15 | + |
| 16 | + |
| 17 | +def create_new_project(name): |
| 18 | + project_folder = Path.cwd().absolute() / name |
| 19 | + project_folder.mkdir() |
| 20 | + (project_folder / "README.md").touch() |
| 21 | + with open(project_folder / ".gitignore", mode="w") as f: |
| 22 | + f.write("\n".join(["venv", "__pycache__"])) |
| 23 | + commands = [ |
| 24 | + [ |
| 25 | + PYTHON_COMMAND, |
| 26 | + "-m", |
| 27 | + "venv", |
| 28 | + f"{project_folder}/venv", |
| 29 | + ], |
| 30 | + ["git", "-C", project_folder, "init"], |
| 31 | + ["git", "-C", project_folder, "add", "."], |
| 32 | + ["git", "-C", project_folder, "commit", "-m", "Initial commit"], |
| 33 | + ] |
| 34 | + for command in commands: |
| 35 | + try: |
| 36 | + subprocess.run(command, check=True, timeout=60) |
| 37 | + except FileNotFoundError as exc: |
| 38 | + print( |
| 39 | + f"Command {command} failed because the process " |
| 40 | + f"could not be found.\n{exc}" |
| 41 | + ) |
| 42 | + except subprocess.CalledProcessError as exc: |
| 43 | + print( |
| 44 | + f"Command {command} failed because the process " |
| 45 | + f"did not return a successful return code.\n{exc}" |
| 46 | + ) |
| 47 | + except subprocess.TimeoutExpired as exc: |
| 48 | + print(f"Command {command} timed out.\n {exc}") |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + parser = ArgumentParser() |
| 53 | + parser.add_argument("project_name", type=str) |
| 54 | + args = parser.parse_args() |
| 55 | + create_new_project(args.project_name) |
0 commit comments