Skip to content

Instantly share code, notes, and snippets.

@baydam
Last active November 25, 2021 13:48
Show Gist options
  • Save baydam/516186bfcb7f3fdae8ae8cd9efefa0bd to your computer and use it in GitHub Desktop.
Save baydam/516186bfcb7f3fdae8ae8cd9efefa0bd to your computer and use it in GitHub Desktop.
Script that generate a Python virtual environment project template compatible with vscode

Generate a Python virtual environment project template compatible with vscode

#!/usr/bin/env python

# This script generate a Python virtual environment project template compatible with vscode
# Author: Dame Diongue
# License: public domain

import os, sys, argparse, json, subprocess, shlex
from shutil import which

def parsed_arguments():
  # Create commandline parser
  parser = argparse.ArgumentParser(description='Generate a Python project template compatible with vscode')
  # Specify the project name
  parser.add_argument('project_name', metavar='project_name')
  # Optional argument: set the virtual enviroment 
  parser.add_argument('-e', '--virtualenv', action='store_true', default=False, help='set the virtual enviroment')
  parser.add_argument('-c', '--vscode', action='store_true', default=False, help='make necessary setting for vscode')
  # Optional argument: set some preinstalled package
  parser.add_argument('-p', '--packages', nargs='+', help='set preinstalled packages', metavar='package(s)')
  # Let's return all parsed arguments
  return parser.parse_args()
      
def setup_virtualenv(vscode=False):
  if vscode:
    os.mkdir('.vscode', mode=0o775)
    settings = {
      "python.pythonPath": "${workspaceFolder}/venv/bin/python",
      "python.venvPath": "${workspaceFolder}/venv"
    }
    # Create vscode setting
    with open('.vscode/settings.json', 'w') as settings_file:
      json.dump(settings, settings_file, indent=2)
  
  # Use python venv if virtualenv is not installed in the system
  if which('virtualenv') is None: 
    execute_command("python -m venv venv")
  else:
    execute_command("virtualenv venv")
    
def execute_command(command):
  # Template for executing command
  command_line = shlex.split(command)
  output = subprocess.Popen(command_line, stdout=subprocess.PIPE)
  output.communicate()
  
def main(argv):
  # Get the command line arguments
  args = parsed_arguments()

  # Create the project folder and enter to it
  os.mkdir(args.project_name, mode=0o755)
  os.chdir(args.project_name)

  # Setup virtual environment
  if args.virtualenv: 
    setup_virtualenv(args.vscode)
  # Check preinstalled packages
  if args.packages and len(args.packages) >= 1:
    file_content = ""
    for pkg in args.packages:
      file_content += pkg + '\n'
    # Write required packages on file
    with open('requirements.txt', 'w+') as package_file:
      package_file.write(file_content)
    # Temporary activate virtual environment and install packages
    os.system('source venv/bin/activate; pip install -r requirements.txt')

if __name__ == "__main__":
    main(sys.argv)

Usage

usage: pyproject.py [-h] [-e] [-c] [-p packages) [package(s ...]] project_name

Generate a Python project template compatible with vscode

positional arguments:
  project_name

optional arguments:
  -h, --help            show this help message and exit
  -e, --virtualenv      set the virtual enviroment
  -c, --vscode          make necessary setting for vscode
  -p package(s) [package(s) ...], --packages package(s) [package(s) ...]
                        set preinstalled packages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment