Python Snippets
Command Line Snippets
Section titled “Command Line Snippets”# Active an environment## Linux Ubuntubashpython3 -m virtualenv ./venvsource ./venv/bin/activatepip install -r requirements.txtpython3 mypythonprogram.py## or use conda instead
## Windows (PowerShell)python -m venv ./venv./venv/Scripts/Activatepip install -r .\requirements.txtpython mypythonprogram.py
## Upgrade a packagepython -m pip install --upgrade pippython -m pip install --upgrade ansible## Upgrade a package as userpython -m pip install --user --upgrade pip## List installed packagespython -m pip list
## Install applications with pipxpipx install ansible## orpython -m pipx install ansible## Upgrade all pipx packagespipx upgrade-all
# See Docstrings of module using pydocpython -m pydoc math# See as HTMLpython -m pydoc -w math
Python Language Snippets
Section titled “Python Language Snippets”Basics
Section titled “Basics”############################# Comments and Doc Strings #############################
# This sentence is a comment"""This sentance is amulti linecomment"""
# Simple Docstring, can be for modules, classes, functionsdef determine_magic_level(magic_number): """ Multiply a wizard's favorite number by 3 to reveal their magic level. """ return magic_number * 3
def picking_hat(): """Return a random house name.""" houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"] return random.choice(houses)
# See Docstring of a module, functionimport mathprint(math.__doc__)print(math.acos.__doc__)help(math)
# Docstring example using reStructuredText (PEP 287 defaut)# Other Docstring types are available like NumPy style common# for data science, Google-style, and doctest that combines# tests with documetationdef cast_spell(wand, incantation, target=None): """ Cast a magical spell using a wand and incantation. This function simulates casting a spell. With no target specified, it is cast into the void.
:param wand: The wand used to do the spell-casting deed. :type wand: str :param incantation: The words said to activate the magic. :type incantation: str :param target: The object or person the spell is directed at (optional). :return: A string describing the result of the spell. :rtype: str
:raises ValueError: If the incantation is unknown or the wand fails to work. """ valid_incantations = ["Lumos", "Alohomora", "Expelliarmus"] if not wand: raise ValueError("You can't cast spells without a wand!") if incantation not in valid_incantations: raise ValueError("Incantation not recognized.") if target: return f"{incantation} hits {target} with magic speed!" return f"{incantation} is cast into the void...sparkles shimmer faintly"
############### Data Types ###############
# String"string3"print("string1")
# Numbers as:## Float3.5## Integers2
############################# Print and with f strings #############################
# String concatenation, adding strings together using +## Convert a float number to string using str()print("20 days are " + str(28800) + " minutes")
# Print a string with f string for variablesprint (f"20 days are {28800} minutes")
# Print a valueprint(f"value={value}")# Print a value conciselyprint(f"{value=}")
####################################### Run operating system shell command #######################################
import os# Call commandos.system('echo "hello world"')
################################## Functions, Built-in Functions ##################################
# Show Pythong executable being usedimport sysprint(sys.executable)
# Print a calculation# Define a new function called days_to_units# function parameter is num_of_days, a local scope variabledef days_to_units_20(): print(f"20 days are {20 * calculation_to_units} {name_of_unit}")
# Get user input# Ask users for input and store user's input in a variable# The input function always returns a string variableuser_input = input("Input a number of days and I will convert it to seconds\n")print(user_input)
# Create a set from a listset(my_list)
# Convert to integerint("20")
# Call built-in function on data type## String split function"2, 3".split()## List count[1, 2, 3].count()
######################### Conditionals, Errors #########################
# Conditional checking, Function# Return number of units in days as string# Validate input is a positive numberdef days_to_units_text_checked(num_of_days): # Check if parameter is a positive number condition_check = num_of_days > 0 # Print the data type of the condition_check variable print(type(condition_check)) # Conditional to check if parameter is a positive number and evaluates to a boolean # true: parameter is a positive number # false: parameter is not a positive number if num_of_days > 0: return f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}" else: return "Enter a positive number, other values or data types are not allowed"
# Exception handling with try except, like catching exceptionstry: # logicexcept ValueError: print("Error: Your input is not a valid number.")
############### While Loop ###############
# While loopwhile user_input != "exit": user_input = input("Enter number of days that this program will convert to hours or type exit to stop\n") validate_and_execute_try_except()
########## Lists ##########
# List: Createlist_of_months = ["January", "February", "March"]
# List: access specific value in list, in this case first elementlist_of_months[0]
# List: Add itemslist_of_months.append("April")
# List: Remove itemslist_of_months.remove("January")
# List: Change itemslist_of_months[0] = "New January"
# String split on a comma to a listmy_list = my_string.split(",")
# Get data type, for example class typetype(my_variable)
############# For loop #############
# Allow user to provide a list of values# Validate all values and return calculationfor num_of_days_elements in user_input.split(", ") validate_and_execute
######### Sets #########
# Set: Apply set to a given listlist_of_months = ["January", "February", "March", "January"]# Set will only contain first 3 months, duplicate January is removedset(list_of_months)
# Set: Create setmy_months_set = {"January", "February", "March"}
# Set: Add elementmy_months_set.add("April")
# Set: Remove elementmy_months_set.remove("April")
# Opening a filewith open(file_path, "r" encoding="utf-8") as file: # do stuff with text file# Open file and print content# Supports read, append, write, create and opening text or binary filesf = open("demofile.txt", "r")print(f.read()
Sources:
- How to Write Docstrings - Real Python
- DevOps Bootcamp - Python Basics - DevOps Bootcamp - Python Basics
- DevOps Bootcamp - Python Automation - DevOps Bootcamp - Python Automation
Other Packages
Section titled “Other Packages”Jupyter notebooks
Section titled “Jupyter notebooks”# Start Jupyter Notebook in current directoryjupyter notebook
# Jupyter Notebook - org conversions## https://michaelneuper.com/posts/replace-jupyter-notebook-with-emacs-org-mode/## Importing existing Jupyter Notebooks into Org Mode## Use jupytext (python package) to convert Jupyter Notebooks to Org Mode files:## Convert your Jupyter Notebook (.ipynb) to an Org Mode file (.org) using the following command:jupytext --to org my_notebook.ipynb## Exporting Org files to Jupyter Notebook formatjupytext --to ipynb my_org_file.org
For Jupyter and notebook use in Emacs org-mode, see Emacs Org Mode Snippets - Emacs Org Mode Snippets
CSV file operations
Section titled “CSV file operations”# Read CSV file with pandasimport pandas as pdcsv_file_path = 'your_file.csv'
# Specify the columns you want to readcolumns_to_read = ['Column1', 'Column2', 'Column3'] # Replace with your actual column names
# Read the specified columns from the CSV filedata = pd.read_csv(csv_file_path, usecols=columns_to_read)
# Display the dataprint(data)
String Operations
Section titled “String Operations”# Regular expressions replacementsimport redef remove_year(text): # This regex matches any year in parentheses, e.g., (2003), (1999), etc. return re.sub(r"\s*\(\d{4}\)", "", text)
# String replace in loop or alonedef clean_string(string_to_clean):
string_cleaned = string_to_clean.trim() # Set of things to replace replacements = { " 4.00": "", " 4.50": "", " 3.13": "", " 4.25": "", " 2.50": "", " 4.75": "", } for original, replacement in replacements.items(): string_cleaned = string_cleaned.replace(original, replacement)
# Replace newlines with two empty spaces return string_cleaned.replace("\n", " ")
HTTP Requests
Section titled “HTTP Requests”-
REST API Endpoint operations GET, POST, PUT, PATCH, DELETE
# Make a get to an API, retrieve dataimport requestsapi_url = "https://jsonplaceholder.typicode.com/todos/1"response = requests.get(api_url)response.json()# {'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}## Check status code and content typeresponse.status_coderesponse.headers["Content-Type"]# Make a post, use json input and set headers, set dataimport requestsapi_url = "https://jsonplaceholder.typicode.com/todos"todo = {"userId": 1, "title": "Buy milk", "completed": False}headers = {"Content-Type":"application/json"}# Serialize the todo json with json.dumps()response = requests.post(api_url, data=json.dumps(todo), headers=headers)# Make a put, update dataimport requestsapi_url = "https://jsonplaceholder.typicode.com/todos/10"response = requests.get(api_url)response.json()todo = {"userId": 1, "title": "Wash car", "completed": True}response = requests.put(api_url, json=todo)response.json()# Do a deleteimport requests# Include ID of item being deletedapi_url = "https://jsonplaceholder.typicode.com/todos/10"response = requests.delete(api_url)response.json()response.status_code