Start New Python Projects Quickly Using a Shell Script

·

2 min read

As someone who loves experimenting with Python libraries and APIs, starting new projects quickly is important. Setting up these projects can sometimes be time-consuming, and a bit annoying to be honest.

Wrote this shell script to automate the process and start coding quickly. Here's what it does -

  • Prompts the user to provide a project name as a command-line argument, and throws an error message and usage instructions if the project name argument is missing.

  • Creates a new project directory with the specified name.

  • Sets up a virtual environment within the project directory.

  • Installs required Python dependencies using pip or a preferred package manager.

  • Creates sub-directories for source code, tests, and documentation.

  • Generates essential files like main.py, requirements.txt, and README.md.

  • Initializes a Git repository for version control.

  • Opens the main.py file in Visual Studio Code in a new window.

Setting up the script

#!/bin/bash

# Check if project name argument is provided
if [ $# -eq 0 ]; then
  echo "Error: Please provide a project name."
  echo "Usage: ./start_python_project.sh <project_name>"
  exit 1
fi

# Get project name as a command-line argument
project_name=$1

# Create project directory
mkdir $project_name
cd $project_name

# Initialize virtual environment
virtualenv -p python3 venv
source venv/bin/activate

# Install dependencies (e.g., requests and numpy)
# pip install numpy

# Create project structure
mkdir src tests docs

# Create main script
touch src/main.py

# Create requirements.txt file
touch requirements.txt

# Create README.md file
touch README.md

# Initialize version control (Git)
git init

# Open main.py in Visual Studio Code in a new window
code --new-window src/main.py

echo "Project setup complete. Happy coding!"

Make the Script Executable

chmod +x start_python_project.sh

Run the Script

./start_python_project.sh my_project

[Optional] Create an alias

  1. Open your shell's configuration file (e.g., .bashrc, .bash_profile) using a text editor,

     nano ~/.bashrc
    
     #or if you're using zsh
     nano ~/.zshrc
    
  2. Add the following line at the end of the file, replacing /path/to/start_python_project.sh with the actual path to your shell script:

     alias newproject='/path/to/start_python_project.sh'
    

Using the script to create a new project

In the terminal, you can now start a new Python project by running the following command, replacing my_project with your desired project name:

newproject <project name>

Fin!