Skip to content

Instantly share code, notes, and snippets.

@lundeen-bryan
Last active March 31, 2023 02:15
Show Gist options
  • Save lundeen-bryan/07fe46a5261a1e71012d0bcf569ff906 to your computer and use it in GitHub Desktop.
Save lundeen-bryan/07fe46a5261a1e71012d0bcf569ff906 to your computer and use it in GitHub Desktop.
python snippets
import os
#from os import system
#HINT: You can call clear() to clear the output in the console.
def clear():
os.system("clear")
# test code to put something on the screen: print("A bunch of stuff")
""" test code to call the function
clear_now = input("Do you want to clear the output? (y/n): ")
if clear_now == "y":
clear()
"""
import os
import json
import sys
import glob
import importlib
import logging
logger = logging.getLogger(__name__)
# Define the import directory
import_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "imports")
)
print(f"\nImporting from: \n{import_dir}\n")
# Add the import directory to the Python module search path
sys.path.append(import_dir)
# Load the configuration file
def load_config():
global config_data
config_path = os.path.join(import_dir, "./config.json")
with open(config_path, "r") as con:
config_data = json.load(con)
print("This is what the config file looks like:")
print(json.dumps(config_data, indent=4))
# Import all modules from the import directory
def import_modules():
global imported_modules
imported_modules = {}
try:
modules = glob.glob(os.path.join(import_dir, "*.py"))
for module in modules:
if module.endswith(".py"):
module_name = module.replace(os.path.sep, ".").replace(
".py", ""
)[len(import_dir) + 1 :]
imported_modules[
module_name.split(".")[-1]
] = importlib.import_module(module_name)
except ImportError as e:
logger.error(f"Error importing module {module_name}: {e}")
print("Imported modules:")
for key, value in imported_modules.items():
print(f"{key}: {value}")
print()
def main():
...
if __name__ == "__main__":
import_modules()
main()
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Project = void 0;
const vscode = require("vscode");
const path = require("path");
const UI_1 = require("./UI");
const fs = require("fs");
class Project {
constructor(context) {
this.dirc = new Array('docs', 'data', 'src', 'imports', 'logs', 'test', 'examples', '.vscode');
this.context = context;
}
async createFiles({ location }) {
try {
const mainPath = path.join(this.context.extensionPath, 'templates', 'main.py');
const reqPath = path.join(this.context.extensionPath, 'templates', 'requirements.txt');
const runPath = path.join(this.context.extensionPath, 'templates', 'run.sh');
const readPath = path.join(this.context.extensionPath, 'templates', 'README.md');
const gitPath = path.join(this.context.extensionPath, 'templates', '.gitignore');
const changelogPath = path.join(this.context.extensionPath, 'templates', 'CHANGELOG.md');
const configPath = path.join(this.context.extensionPath, 'templates', 'config.json');
const importPath = path.join(this.context.extensionPath, 'templates', '_clear_console.py');
fs.writeFileSync(path.join(location, 'src', 'main.py'), fs.readFileSync(mainPath, "utf-8"));
fs.writeFileSync(path.join(location, 'requirements.txt'), fs.readFileSync(reqPath, "utf-8"));
fs.writeFileSync(path.join(location, "run.sh"), fs.readFileSync(runPath, "utf-8"));
fs.writeFileSync(path.join(location, "README.md"), fs.readFileSync(readPath, "utf-8"));
fs.writeFileSync(path.join(location, ".gitignore"), fs.readFileSync(gitPath, "utf-8"));
fs.writeFileSync(path.join(location, "CHANGELOG.md"), fs.readFileSync(changelogPath, "utf-8"));
fs.writeFileSync(path.join(location, 'imports', 'config.json'), fs.readFileSync(configPath, "utf-8"));
fs.writeFileSync(path.join(location, 'imports', '_clear_console.py'), fs.readFileSync(importPath, "utf-8"));
vscode.workspace.openTextDocument(path.join(location, 'src', 'main.py')).then(doc => vscode.window.showTextDocument(doc, { preview: false }));
}
catch (err) {
console.error(err);
}
}
async createFolders(location) {
const dirSubdirPairs = [
{ dir: 'docs', subdirs: ['research', 'tutorials'] },
{ dir: 'data', subdirs: ['excel', 'pdf', 'jupyter', 'sql'] },
{ dir: 'src' },
{ dir: 'imports' },
{ dir: 'logs' },
{ dir: 'test' },
{ dir: 'examples' },
{ dir: '.vscode' },
// add more directory and subfolder pairs here as needed
];
for (let pair of dirSubdirPairs) {
const { dir, subdirs } = pair;
try {
fs.mkdirSync(path.join(location, dir));
if (subdirs) {
for (let subdir of subdirs) {
fs.mkdirSync(path.join(location, dir, subdir));
}
}
}
catch (err) {
console.error(err);
}
}
}
async createProject() {
const result = await UI_1.UI.openDialogForFolder();
if (result && result.fsPath) {
await vscode.commands.executeCommand('vscode.openFolder', result);
await this.createFolders(result.fsPath);
await this.createFiles({ location: result.fsPath });
}
}
}
exports.Project = Project;
//# sourceMappingURL=project.js.map
{
"Check Main": {
"prefix": "pymain",
"body": "if __name__ == '__main__':",
"description": "will insert the main call",
},
"Header": {
"prefix": "pyHeader",
"body": [
"$LINE_COMMENT$LINE_COMMENT===========================================================================================",
"$LINE_COMMENT$LINE_COMMENT Date: .............. ${1:$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE}",
"$LINE_COMMENT$LINE_COMMENT Program: ........... $TM_FILENAME",
"$LINE_COMMENT$LINE_COMMENT Website: ........... ${2:weburl}",
"$LINE_COMMENT$LINE_COMMENT Description: ....... ${3:description}",
"$LINE_COMMENT$LINE_COMMENT Installs to: ....... ${TM_DIRECTORY/.*\\\\(.*)\\\\(.*)$/$1\\/$2/}",
"$LINE_COMMENT$LINE_COMMENT Compatibility: ..... ${4:Excel,Word,etc.}",
"$LINE_COMMENT$LINE_COMMENT Contact Author: .... ${5:author}",
"$LINE_COMMENT$LINE_COMMENT Copyright © ........ ${6:company} $CURRENT_YEAR. All rights reserved.",
"$LINE_COMMENT$LINE_COMMENT Called by: ......... ${7:other_subs}",
"$LINE_COMMENT$LINE_COMMENT Called to: ......... ${8:other_subs}",
"$LINE_COMMENT$LINE_COMMENT Arguments: ......... ${9:parameters}",
"$LINE_COMMENT$LINE_COMMENT",
"$LINE_COMMENT$LINE_COMMENT Notes:",
"$LINE_COMMENT$LINE_COMMENT",
"$LINE_COMMENT$LINE_COMMENT",
"$LINE_COMMENT$LINE_COMMENT===========================================================================================\n\n\n$0"
],
"description": "insert module description"
},
"Update Code": {
"prefix": "pyHeaderUpdate",
"body": [
"$LINE_COMMENT$LINE_COMMENT Updated: .............. ${1:$CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE}",
"$LINE_COMMENT$LINE_COMMENT Updated by: ........... ${2:author}",
"$LINE_COMMENT$LINE_COMMENT Changes made: ......... _",
" (${3:change number}) ${4:description}",
]
},
"dictionary comprehension from list": {
"prefix": "py-dict-comp1",
"body": [
"${1:new_dictionary_name} = {${3}:${4:value_to_add} for ${3:item_in_list_as_key} in ${2:list}}",
],
"description": "create a new dictionary from an iterable list"
},
"dictionary comprehension from list with condition": {
"prefix": "py-dict-comp2",
"body": [
"${1:new_dictionary_name} = {${3}:${4:value_to_add} for ${3:item_in_list_as_key} in ${2:list} if ${5:condition}}",
],
"description": "create a new dictionary from an iterable list if condition is met"
},
"dictionary comprehension from a dictionary": {
"prefix": "py-dict-comp3",
"body": [
"${1:new_dictionary_name} = {${3}:${5:value_from_formula} for (${3:key_in_dict}, ${4:item_in_list}) in ${2:list}.items()}",
],
"description": "create a dictionary from a dictionary and change the value but same key"
},
"dictionary comprehension from a dictionary with condition": {
"prefix": "py-dict-comp4",
"body": [
"${1:new_dictionary_name} = {${3}:${5:value_from_formula} for (${3:key_in_dict}, ${4:item_in_list}) in ${2:list}.items() if ${6:condition}}",
],
"description": "create a dictionary from a dictionary and change the value but same key if condition is met"
},
"list comprehension - instead of for loop": {
"prefix": "py-list-comp1",
"body": [
"${1:new_list_name} = [${3:value_from_formula} for ${4:item_in_list} in ${2:list_or_value_from_formula}]",
],
"description": "create a list by iterating through another list"
},
"list comprehension - instead of for loop with condition": {
"prefix": "py-list-comp2",
"body": [
"${1:new_list_name} = [${3:value_from_formula} for ${4:item_in_list} in ${2:list_or_value_from_formula} if ${5:condition}]",
],
"description": "create a list by iterating through another if condition is met"
},
"comment-block": {
"prefix": "comment-block",
"body": "\n'''\n *\n * ${1:Block comment}\n *\n'''\n\n",
"description": "Comment: Block style",
},
"comment-section-header": {
"prefix": "comment-section-header",
"body": "\n'''=============================================\n= ${1:Section comment block} =\n============================================='''\n\n$2\n\n",
"description": "Comment: Section header",
},
"comment-section-footer": {
"prefix": "comment-section-footer",
"body": "\n'''===== End of ${1:Section comment block} ======'''\n\n",
"description": "Comment: Section footer",
},
"comment-section": {
"prefix": "comment-section",
"body": "\n'''============================================\n= ${1:Section comment block} =\n===============================================\n$2\n\n======== End of ${1:Section comment block} ===='''\n\n",
"description": "Comment: Full section",
},
"comment-subsection": {
"prefix": "comment-subsection",
"body": "\n'''---------- ${1:Subsection comment block} ----------'''\n\n",
"description": "Comment: Subsection",
},
"comment before": {
"prefix": "\/\/comment-before",
"body": "\n''' ${1:Comment} \n'''\n$0",
"description": "Comment: Single-line block",
},
"comment": {
"prefix": "\/\/comment-after",
"body": "\n# ${1:Comment} \n\n$0",
"description": "line-break then comment after code",
},
"jupyter-plot": {
"prefix": "jupyter-plot",
"body": [
"# %%",
"## imports plotly: pyo, go; pandas; xlwings; numpy;",
"# import plotly.offline as pyo",
"# import plotly.graph_objects as go",
"# import plotly.figure_factory as ff",
"# import plotly.io as io # use instead of pyo",
"# import pandas as pd",
"# import numpy as np",
"# import xlwings as xw",
"",
"# %%",
"## Read in data to data frame using pandas",
"df = pd.read_csv(\"${1:datasource}\")",
"df.shape # show the col/rows of the df",
"df.info()",
"",
"# %%",
"## view the dataframe",
"pd.options.display.min_rows=${2:number}",
"# |df,xw.view(df),df.head(),df.to_markdown()|",
"",
"# %%",
"## create data variable using list/dict comprehension",
"data = []",
"",
"# %% Create layout",
"layout = go.Layout(title=\"${3:title}\")",
"",
"# %%",
"## Create figure",
"fig = go.Figure(data=data, layout=layout)",
"",
"# %%",
"## Load plot to html",
"pyo.plot(fig, filename=\"${4:filename}\")",
""
],
"description": "This inserts a chart to using plotly",
},
}
#!/bin/bash
# Clear the terminal screen
clear
# Set up the trap to catch the SIGINT signal
trap 'kill $PID; exit 1' INT
# Notify the user that the virtual environment is being created
echo "Creating virtual environment. Please wait..."
# Create a Python virtual environment in the background
python -m venv .venv &
PID=$!
# Wait for the virtual environment to be created
wait $PID
# Add the hidden attribute to the .venv directory
if [[ "$OSTYPE" == "darwin"* ]]; then
SetFile -a V .venv
else
attrib +h .venv
fi
# Wait for the user to press any key before continuing
read -p "Virtual environment created. Press Enter to activate and install dependencies..."
# Activate the Python virtual environment
source .venv/Scripts/activate
# Upgrade pip
python -m pip install --upgrade pip
# Install the Python package dependencies specified in requirements.txt
pip install -r requirements.txt
# Ask user if they want to run main.py
read -p "Do you want to run main.py? (yes/no) " run_main
# Execute the main.py Python script if the user answered "yes"
if [[ "$run_main" == "yes" ]]; then
python ../src/main.py
fi
# Pause the script and wait for the user to press Enter
read -p "Hit Enter to close..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment