Skip to content

Instantly share code, notes, and snippets.

@pip182
Last active July 14, 2020 21:30
Show Gist options
  • Save pip182/a845e5d5b4410c2d94fa557ca844b260 to your computer and use it in GitHub Desktop.
Save pip182/a845e5d5b4410c2d94fa557ca844b260 to your computer and use it in GitHub Desktop.
A collection of python scripts / functions
Some python scripts and functions that I would like to reference back to in the future.
# To easily use colors in the CLI you can use this class
class colors:
'''Colors class:
reset all colors with colors.reset
two subclasses fg for foreground and bg for background.
use as colors.subclass.colorname.
i.e. colors.fg.red or colors.bg.green
also, the generic bold, disable, underline, reverse, strikethrough,
and invisible work with the main class
i.e. colors.bold
'''
reset = '\033[0m'
bold = '\033[01m'
disable = '\033[02m'
underline = '\033[04m'
reverse = '\033[07m'
strikethrough = '\033[09m'
invisible = '\033[08m'
class fg:
black = '\033[30m'
red = '\033[31m'
green = '\033[32m'
orange = '\033[33m'
blue = '\033[34m'
purple = '\033[35m'
cyan = '\033[36m'
lightgrey = '\033[37m'
darkgrey = '\033[90m'
lightred = '\033[91m'
lightgreen = '\033[92m'
yellow = '\033[93m'
lightblue = '\033[94m'
pink = '\033[95m'
lightcyan = '\033[96m'
class bg:
black = '\033[40m'
red = '\033[41m'
green = '\033[42m'
orange = '\033[43m'
blue = '\033[44m'
purple = '\033[45m'
cyan = '\033[46m'
lightgrey = '\033[47m'
cabs = Cabinet.objects.filter(room__bid__approved_by_dealer__isnull=False).filter(room__bid__date__range=['2019-07-14', '2021-01-01']).filter(deleted__isnull=True)
newcabs = cabs.exclude(room__cabinet_box_interior__pk__in=[1, 24]).filter(room__bid__order_type=1)
# Write file for newcabs
with open("fin_ends.csv", "wb") as csvfile:
filew = csv.writer(csvfile)
for c in newcabs:
filew.writerow([c.room.bid.approved_by_dealer.strftime("%m-%d-%y"),
c.room.id, c.room.bid.id, c.room.cabinet_box_interior, c.room.wood_type,
int(c.finished_left), int(c.finished_right), int(c.finished_top),
int(c.finished_bottom), int(c.finished_interior)])
newcabs = cabs.filter(room__cabinet_box_interior__pk__in=[1, 24]).filter(room__bid__order_type=1)
newcabs = newcabs.exclude(room__wood_type__pk__in=[1, 77, 2, 39, 40, 344, 67, 9, 78, 28, 75, 34, 259, 33])
for c in newcabs:
filew.writerow([c.room.bid.approved_by_dealer.strftime("%m-%d-%y"),
c.room.id, c.room.bid.id, c.room.cabinet_box_interior, c.room.wood_type,
int(c.finished_left), int(c.finished_right), int(c.finished_top),
int(c.finished_bottom), int(c.finished_interior)])
# Write file for cabs
with open("total_cabs.csv", "wb") as csvfile:
filew = csv.writer(csvfile)
for c in cabs:
if c.is_cabinet:
filew.writerow([c.room.bid.approved_by_dealer.strftime("%m-%d-%y"),
c.room.id, c.room.bid.id, c.room.cabinet_box_interior, c.room.wood_type,
int(c.finished_left), int(c.finished_right), int(c.finished_top),
int(c.finished_bottom), int(c.finished_interior)])
# A simple example where we make a decorator that can be passed 'self'
import functools
# Decorator for blocking QT signals
def BlockSignals(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
self.blockSignals(True)
func(self, *args, **kwargs)
self.blockSignals(False)
return wrapper
#!/usr/bin/python3
# An example of sending an email through Google usuing smtplib
import smtplib
import datetime
import re
import sys
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Create a file to log errors if they happen
sys.stderr = open(os.path.dirname(os.path.abspath(__file__)) + '/error.log', 'w')
def remove_tags(text):
" Strips html tags to convert to plain text. "
TAG_RE = re.compile(r'<[^>]+>')
return TAG_RE.sub('', text)
def truncate(text, length):
" Cuts off text longer than 'length', leaving ellipsis (...) at the end. "
return text[:length] + '...' if len(text) > length else text
# Initialize e-mail stuff...
print("Initializing email.")
try:
# Email from
mail_from = 'SOMEGUY@gmail.com'
mail = smtplib.SMTP_SSL('smtp.gmail.com', 465)
mail.ehlo()
# Email Password and login
mail.login(mail_from, 'PASSWORD')
except Exception:
print("Didn't work! Email borked...")
quit()
# A dictionary containing the email address to send to.
users = {'dude':
{'name': 'Dude Man', 'email': 'dudeman@gmail.com'},
}
# Generate the recipient email addresses, we need to be a list of strings.
mail_to_list = [users[u]["email"] for u in users if users[u]["email"]]
# Today's date, formatted as {Month Day, Year}
today = datetime.date.today().strftime("%B %d, %Y")
# The beggining of the message body with HTML tags
msg = """<div style="font-size:11pt;">
<h3>Testing - {today}</h3>
<p>Just testing to make sure Google EMail stuff works...</p>
<br>""".format(today=today)
print("Sending emails to: {mail_to}!".format(mail_to=str(mail_to_list)))
# Should be self explanitory... uses 'alternative' to provide a Non HTML message alond with an HTML version
message = MIMEMultipart('alternative')
message['Subject'] = "Testing - {today}".format(today=today)
message['From'] = mail_from
message['Cc'] = ','.join(email for email in mail_to_list)
# Create aPlain Text version of the message and attach it to the message.
message.attach(MIMEText(remove_tags(msg), 'plain'))
# The HTML version from above, attach to message.
message.attach(MIMEText(msg, 'html'))
# Finally send the email and quit
mail.sendmail(mail_from, mail_to_list, message.as_string())
mail.quit()
print("Done!")
import re
def remove_tags(text):
" Strips html tags to convert to plain text. "
TAG_RE = re.compile(r'<[^>]+>')
return TAG_RE.sub('', text)
def truncate(text, length):
" Cuts off text longer than 'length', leaving ellipsis (...) at the end. "
return text[:length] + '...' if len(text) > length else text
# Script parses the formula (v) and applies it to the price (p)
v = "+$10023 -%50"
p = 35000.37
def calcit(formula, price):
v = formula.split(" ")
oldprice = price
for i in v:
try:
num = float(i[2:])
if i[1] == "%":
price = eval('price {0} price * (num / 100)'.format(i[0]))
elif i[1] == "$":
price = eval('price {0} num'.format(i[0]))
except:
continue
return {'price': price, 'oldprice': oldprice, 'diff': price - oldprice}
print(calcit(v, p)['price'])
# Use the fbs build system to create a quick QT5 app
# https://github.com/mherrmann/fbs-tutorial
# <----------------------------------------------------------------------------->
# < Subprocess example >
# <----------------------------------------------------------------------------->
#
# Shows how to use subprocess to run multiple external applications simultaniously.
import subprocess
# Create a set where we will store the subprocesses
processes = set()
# Run's a custom script "remount" which gets sent an argument of 0
# This is identical to typing out "bash /home/homestead/bin/remount 0" in a shell
subprocess.run(["bash", "/home/homestead/bin/remount", "0"])
# Output text, some terminal emulators such as WebMin will not worth with the print() function so echo it is.
subprocess.run(["echo", "\nThis can take a few minutes, wait for it to finish completely."])
# Runs a copy of rsync for everything in a list or other object. each one will run in its own process.
# Adds each instance to the processes set we defined above.
for i in some_object:
processes.add(subprocess.Popen(['rsync', i['from'], i['to']]))
# Waits until all processes are finished.
for p in processes:
if p.poll() is None:
p.wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment