Python Scripts: Difference between revisions

1,613 bytes removed ,  6 years ago
 
(8 intermediate revisions by the same user not shown)
Line 678:
</syntaxhighlight>
 
= ExtensionsPython correctorDice =
Source: [https://askubuntu.com/questions/631900/correct-file-extensions askubuntu.com]
 
<syntaxhighlight lang="python">
#!/usr/bin/env python3
from tkinter import *
from random import randint
import sys
 
root = Tk()
# Append _(1) if existing file
# Duplicate remover
# Webp Conv failed > do not rm file
# HAUceV0.jpg.jpg => not renamed when image not supported
# use dwebp 1.webp -o - | convert - 1.jpg
# Do not run command recursively
 
header = Label(root, text="Dice App v1.0", font=("Times", 35))
import os, re, sys, glob
header.pack()
import imghdr, shutil
import subprocess, tarfile
from pathlib import Path
 
photo = PhotoImage(file="dice.gif")
try:
directory = sys.argv[1]
except:
print("\nException occured: Full Directory path with images not defined.\n")
sys.exit()
 
label = Label(image=photo)
# Code for Archiving existing files & save list of files
label.pack(side=RIGHT)
# Delete Archive if no of files is same
 
e = Entry(root, width=10, font=("Helvetica", 30, "bold"), justify=CENTER)
print("---=========== Started backup of files =============---")
e.pack()
 
e.delete(0, END)
tar = tarfile.open("backup.tar.gz", "w:gz")
e.insert(0, "Ready!!")
wr = open("file_list.txt", "w")
wr.write("List of files:\n\n")
x = 0
 
def dice():
for name in glob.glob(os.path.join(directory, '*')):
wre.writedelete(name0, + '\n'END)
tare.addinsert(name0, randint(1,6))
x += 1
wr.close()
tar.close()
 
def exit():
print ("Initial No of Files: ", x)
print("Bye Bye!!")
sys.exit()
 
a = Button(root, text="Roll Dice", width=20, command=dice)
a.pack()
 
f = Button(root, text="Exit App", width=20, fg="Red", command=exit)
# Code to add Ext if not present & remove double Ext
f.pack()
 
root.geometry("400x200")
print("\n---=========== Started Unique extensions =============---\n")
root.mainloop()
</syntaxhighlight>
 
for root, dirs, files in os.walk(directory):
for name in files:
file = root +"/"+ name
 
= Weather Parcer =
# find double extensions
*Need to register a account & get API Key from http://openweathermap.org
fn1, ext1 = os.path.splitext(file)
fn2, ext2 = os.path.splitext(fn1)
ftype = imghdr.what(file)
 
<syntaxhighlight lang="py>
if ftype == None:
import socket
print(file, "Unsupported file")
import json
else:
newname = file +"."+ ftype
if not ext1:
filechk2 = Path(newname)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwriting")
else:
shutil.move(file, newname)
print (file, "has no ext, Appending:", ftype)
else:
if not ext2:
# print("1 Extension only")
continue
elif ext2 == ext1:
filechk = file.replace(ext1,ftype)
filechk2 = Path(filechk)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwritting")
else:
shutil.move(file, fn1.replace(ext2,ext1))
print (file, "has 2 Same ext, Removing:", ext2)
elif ext2 != ext1:
filechk = file.replace(ext1,ftype)
filechk2 = Path(filechk)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwritting")
else:
shutil.move(file, fn1.replace(ext2,ext1))
print (file, "has 2 Diff ext, Removing:", ext2)
else:
print ("Something wrong with file or logic")
 
s = socket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
 
s.connect(addr[0][4])
# Code to Correct File Extensions
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
print("\n---=============== Started correcting extension ================---\n")
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div)
 
main = data['weather'][0]['main']
for root, dirs, files in os.walk(directory):
print("Main =", main)
for name in files:
file = root+"/"+name
 
desc = data['weather'][0]['description']
# find the correct extension
print("Description =", desc)
ftype = imghdr.what(file)
ext = os.path.splitext(file)[1][1:]
 
Celcius = data['main']['temp'] - 273.15
# find files with the (incorrect) extension to rename
rnd = str(round(Celcius,2))
if ext:
print("Temperature =", rnd, "\xb0C")
if ftype != ext:
if ftype != None:
if (ftype == "jpeg") & (ext == "jpg"):
continue
# print(file, "File type is JPG/JPEG, ignoring")
else:
filechk = file.replace(ext,ftype)
filechk2 = Path(filechk)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwritting")
else:
# rename the file
shutil.move(file, file.replace(ext,ftype))
print (file, ext, ("=>"), ftype)
# in case it can't be determined, mention it in the output
else:
if ext == "png":
filechk = file.replace(ext,"jpg")
filechk2 = Path(filechk)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwritting")
else:
shutil.move(file, file.replace(ext,"jpg"))
print (file, "File type not determined for PNG =>", file.replace(ext,"jpg"))
else:
print(file, "Could not determine file type")
else:
continue
# print(file, "Correct Extension")
else:
print(file, "No Extension detected")
 
pres = data['main']['pressure']
print("Pressure =", pres, "mbar")
 
hum = data['main']['humidity']
# Code to convert WEBP to PNG
print("Humidity =", hum, "%")
 
vis = int(data['visibility'])/1000
print("\n---================== Started WEBP to PNG conversion ===============---\n")
print("Visibility =", vis, "Km?")
 
speed = data['wind']['speed']
for root, dirs, files in os.walk(directory):
try:
for name in files:
filedir = root + "/" + namedata['wind']['deg']
except KeyError:
dir = 0
fn, ext = os.path.splitext(file)
rnd2 = str(round(dir,2))
if ext == ".webp":
print("Wind Speed =", speed, "Km/h?")
fnpng = fn + ".png"
print("Wind Direction =", rnd2, "Degree")
fpath = Path(fnpng)
</syntaxhighlight>
if fpath.is_file():
print (fnpng, "File already EXISTS, not overwritting")
else:
conv = subprocess.Popen(["dwebp", file, "-o", fnpng], stdout=subprocess.PIPE)
output, err = conv.communicate()
rmfile = subprocess.Popen(["rm", file], stdout=subprocess.PIPE)
output2, err2 = rmfile.communicate()
else:
continue
# print (file, "File is not Webp, Skipping")
 
= Plot Temperature using Thingspeak =
*Need to register a account & get API Key from http://openweathermap.org
*Need to register a account & get API Key from http://thingspeak.com
 
== Upload Temperature ==
# Code to replace : with _ in file names
 
<syntaxhighlight lang="py>
print("\n---=============== Started Colon replace space =============---\n")
import socket
import json
from time import strftime,localtime,sleep
 
while True:
for root, dirs, files in os.walk(directory):
# Fetch Temperature from openweathermap.org
for name in files:
files = root + "/" + namesocket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
if re.search(r':', file):
filechk = file.replace(":","_")
filechk2 = Path(filechk)
if filechk2.is_file():
print (filechk2, "File already EXISTS, not overwriting")
else:
# rename the file
shutil.move(file, file.replace(":","_"))
print (file, ("Colon => "), file.replace(":","_"))
else:
continue
# print(name, " Colon Not Found in name")
 
s.connect(addr[0][4])
print("\n---===================== All Done =======================---\n")
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
 
html = s.recv(1000)
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div.decode('utf-8'))
 
cel = data['main']['temp'] - 273.15
# Code to verify if any file missing, deleted, overwritten
temp = float(round(cel,2))
y = 0
 
# Upload Temperature Data to thingspeak.com
for name in glob.glob(os.path.join(directory, '*')):
ys2 += 1socket.socket()
addr2 = socket.getaddrinfo('api.thingspeak.com', 80)
 
s2.connect(addr2[0][4])
print ("Initial No of Files: ", x)
s2.send(b'POST https://api.thingspeak.com/update?api_key=XB15HC17CZH6KYMV_1&field1=%f HTTP/1.0\r\n\r\n' % temp)
print ("Final No of Files: ", y)
html2 = s2.recv(1000)
div2 = html2.split(b' ')[1]
 
# Check if logged data successfully
if x == y:
if int(div2) == 200:
print("Operation completed successfully")
currtime = strftime("%H:%M:%S %d-%b-%Y", localtime())
else:
print("OperationUploaded failedData @", somecurrtime,":", files"Temp missing=", temp, "\xb0C")
else:
print("HTTP Error:", int(div2))
 
# Wait for 10 minutes
sleep(600)
</syntaxhighlight>
 
== Bulk Upload Parameters ==
 
= Python Dice =
 
<syntaxhighlight lang="python">
import socket
#!/usr/bin/env python3
from tkinter import *json
from randomtime import randintstrftime,localtime,sleep
import sysrequests
 
# Fetch Temperature from openweathermap.org
root = Tk()
def weather():
s = socket.socket()
addr = socket.getaddrinfo('api.openweathermap.org', 80)
s.connect(addr[0][4])
s.send(b'GET http://api.openweathermap.org/data/2.5/weather?q=Bangalore&units=metric&appid=84d996853fcc4db149bc40acb09a3ef7_1 HTTP/1.0\r\n\r\n')
html = s.recv(1000)
s.close()
div = html.split(b'\r\n\r\n')[-1]
data = json.loads(div.decode('utf-8'))
return data
 
def thing():
header = Label(root, text="Dice App v1.0", font=("Times", 35))
# Call weather function
header.pack()
data = weather()
temp = data['main']['temp']
pres = data['main']['pressure']
hum = data['main']['humidity']
vis = int(data['visibility'])/1000
speed = data['wind']['speed']
try:
dir = data['wind']['deg']
except KeyError:
dir = 0
ctime = strftime("%Y-%m-%d %H:%M:%S +0530", localtime())
print("Data Fetched @",ctime,":","Temp(C)=",temp,"\xb0C","Press(hPa)=",pres,"Hum(%)=",hum,"Vis(Km)=",vis,"Speed(m/s)=",speed,"Dir(deg)=",dir)
# Upload Temperature Data to thingspeak.com
payload = {"write_api_key":"G97NZS1XWXCS798C_1","updates":[{"created_at":ctime,"field1":temp,"field2":pres,"field3":hum,"field4":vis,"field5":speed,"field6":dir}]}
url = 'https://api.thingspeak.com/channels/396314/bulk_update.json'
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
return response
 
while True:
photo = PhotoImage(file="dice.gif")
response = thing()
 
# Check if logged data successfully
label = Label(image=photo)
if response.status_code == 202:
label.pack(side=RIGHT)
print("Data successfully uploaded :", response.status_code)
else:
print("HTTP Error Code:", response.status_code)
 
# Wait for 10 minutes
e = Entry(root, width=10, font=("Helvetica", 30, "bold"), justify=CENTER)
sleep(600)
e.pack()
</syntaxhighlight>
 
== Slack Webhook POST ==
e.delete(0, END)
<syntaxhighlight lang="python">
e.insert(0, "Ready!!")
#!/usr/bin/python
import json
import requests
 
requests.packages.urllib3.disable_warnings()
def dice():
e.delete(0, END)
e.insert(0, randint(1,6))
 
# Create the webhook at https://my.slack.com/services/new/incoming-webhook/
def exit():
webhook_url = 'https://hooks.slack.com/services/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'
print("Bye Bye!!")
slack_data = {'text': "Sev1 Incident: Pool is Down :skull:"}
sys.exit()
 
response = requests.post(
a = Button(root, text="Roll Dice", width=20, command=dice)
webhook_url, data=json.dumps(slack_data),
a.pack()
headers={'Content-Type': 'application/json'}
 
)
f = Button(root, text="Exit App", width=20, fg="Red", command=exit)
if response.status_code != 200:
f.pack()
raise ValueError(
 
'Request to slack returned an error %s, the response is:\n%s'
root.geometry("400x200")
% (response.status_code, response.text)
root.mainloop()
)
</syntaxhighlight>