• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

Simple Python Scripts

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
This thread is for very simple python scripts or python code snippets.

As promised here:
http://forums.techpowerup.com/showpost.php?p=1752052&postcount=14

A Simple Python RSS Feed parser for the Tech Power Up site only.

There are better libraries to use and better ways of parsing an RSS feed,
but it's not a bad learning script.
Code:
#!/usr/bin/python

import sys
import string
from urllib2 import urlopen
import xml.dom.minidom

var_xml = urlopen("http://www.techpowerup.com/rss/")
var_all = xml.dom.minidom.parse(var_xml)

var_page_title = var_all.getElementsByTagName("title")[0].firstChild.data
var_page_link = var_all.getElementsByTagName("link")[0].firstChild.data
var_page_editor = var_all.getElementsByTagName("managingEditor")[0].firstChild.data
var_page_date = var_all.getElementsByTagName("pubDate")[0].firstChild.data
var_page_description = var_all.getElementsByTagName("description")[0].firstChild.data

print "--------------------------------------------------"
print "RSS Feed Title:  ", var_page_title  
print "URL Link:        ", var_page_link
print "Managing Editor: ", var_page_editor
print "Published Date:  ", var_page_date
print " "
print var_page_description
print "--------------------------------------------------"
print " "

for item in var_all.getElementsByTagName('item'):
   var_title = item.getElementsByTagName('title')[0].firstChild.data
   var_link = item.getElementsByTagName('link')[0].firstChild.data
   var_description = item.getElementsByTagName('description')[0].firstChild.data
   var_date = item.getElementsByTagName('pubDate')[0].firstChild.data
   var_author = item.getElementsByTagName('author')[0].firstChild.data

   print "Title:           ", var_title  
   print "URL Link:        ", var_link
   print "Author:          ", var_author
   print "Published Date:  ", var_date
   print " "
   print var_description
   print "--------------------------------------------------"
   print " "

Here is an image of it running in a shell on my desktop.
(I piped it into "more" so it would stop on the first page)


MORE SCRIPTS TO COME
 
Joined
Nov 27, 2007
Messages
2,255 (0.38/day)
System Name HOMECOMPUTER
Processor Intel i9 - 9900k @ 5.1Ghz - 1.31v
Motherboard Asux ROG Maximus XI Hero Wifi
Cooling ek supremacy evo full nickle, 2xEK 360 Radiators, ek d5 pump/res combo, ek full cover 2080ti block
Memory 16GB DDR 3600 Trident Z RGB
Video Card(s) Gigabyte RTX 2080TI
Storage 1xWD black NVME 500GB, 1xSamsung 970 Evo Plus NVME 1TB
Display(s) 2 Dell Gaming 27" 1440P Gsync
Case Lian LI PC-011 Dynamic
Audio Device(s) onboard
Power Supply Evga P2 1200Watt
Mouse Zowie FK1+
Keyboard Corsair Strafe rgb silent
Software Windows 10 Pro
Benchmark Scores i'm working on that
wow awsome... yeah i heard it was a good language to start with.. i haven't got far but hopefully these examples will give me an idea on what to do with them..

btw do you think i should roll my asus g71 over to linux and learn about the shell and the like and do my python programming there?
 

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
Hey exodusprime1337,
Just got in from shoveling snow :(

I'm all for suggesting Linux to people, but...
I've also learned to keep my variables to a minimum.
What I'm saying is, when learning something new,
Python in this case, you don't want to add Linux and the
shell into the mix as debugging is harder with 2 unknowns.

Stick with your tried and true environment when experimenting
w/ Python and when you have time to focus on Linux only
start messing w/ shell scripting, perl and tcl/tk.
Then you'll realize that you can do everything on Linux.

For now just remove my she-bang line
Code:
#!/usr/bin/python
as it's only function is to tell the Linux kernel what interpreter to use.

I'll have another script for you tonight :)
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Thanks Regex !! Not a lot of Python posts on P&W.
You get to be the Python Guru. lol

I wrote a windows app in C# for getting the TPU (or any) RSS feed, but it was just one of those "coding for fun" projects.

Anyway, nice job. :toast:
 

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
Ha! Ha! Thanks for the kind words Kreij,
but I'm just a hack :eek:

When it comes to swimming in python,
I would be the one drowning in the kiddie pool :laugh:

Beginner scripts are really all I'm good for and
the posted script is only good for showing how to open a URL
and do a little XML parsing.

Databases are more my thing ;)
 
Joined
Nov 27, 2007
Messages
2,255 (0.38/day)
System Name HOMECOMPUTER
Processor Intel i9 - 9900k @ 5.1Ghz - 1.31v
Motherboard Asux ROG Maximus XI Hero Wifi
Cooling ek supremacy evo full nickle, 2xEK 360 Radiators, ek d5 pump/res combo, ek full cover 2080ti block
Memory 16GB DDR 3600 Trident Z RGB
Video Card(s) Gigabyte RTX 2080TI
Storage 1xWD black NVME 500GB, 1xSamsung 970 Evo Plus NVME 1TB
Display(s) 2 Dell Gaming 27" 1440P Gsync
Case Lian LI PC-011 Dynamic
Audio Device(s) onboard
Power Supply Evga P2 1200Watt
Mouse Zowie FK1+
Keyboard Corsair Strafe rgb silent
Software Windows 10 Pro
Benchmark Scores i'm working on that
well that makes you a guru in my book.. writing 1 line of code and remembering how i did it is a struggle atm, so i'm still swimming in a teaspoon lol.
 

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
Before we post any more scripts, I'd like to take
a step back and go over the basic help function
within the Python interactive console.
(mine is on linux, not sure if the Windows version is exactly the same) :confused:

Here I start the Python console, it tells me what
version I'm using and gives me a >>> prompt



Now I use the HELP function to view all the installed modules/libraries
Code:
help("modules")





Now to see what functions are contained within a particular module,
we simply use help again. I'll be looking at the webbrowser module
which can be seen in the list.
Code:
help("webbrowser")





By looking into the module, I see that I want to use the open_new(url) function,
so my command(s) will look someting like this.
I have to import the module to use the functions.

Code:
>>> import webbrowser
>>> webbrowser.open_new("http://techpowerup.com/")

As you can see from the image, my default browser opened to
the specified url from within Python.



Help can navigate through any module, exposing the various
functions which I hope will make your python coding easy and fun :D

Now lets do some scripting. ;)
 

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
Some Python Database Scripts

Here are some Python Sqlite Database Scripts.

You need the sqlite3 module installed,
(but it's normally part of the initial Python install package)

This first script creates the DATABASE and TABLE:

Code:
#!/usr/bin/python

import sqlite3

try:
   #Here is where we create the database
   var_connection = sqlite3.connect("linux_database.db")

   #Now we create the cursor for access
   var_cursor = var_connection.cursor()

   #Now we create a database table
   var_cursor.execute('''CREATE TABLE
                      linux_table(distro VARCHAR(15),
                      version VARCHAR(5),
                      type VARCHAR(10))''')

   var_connection.commit()
   var_connection.close()

   print ""
   print "linux_database DATABASE has been created"
   print "distro_table TABLE has been created"
   print ""

except (ImportError, RuntimeError, TypeError, NameError):
   print ""
   print "Error, exception thrown"
   print ""

Image of this script running on my system:




This next script inserts pre-defined data into the newly created table.
The pre-defined data is contained within multiple TUPLES and the
tuples are contained within a LIST.

Code:
#!/usr/bin/python

import sqlite3

try:
   #Here is where we connect to the database
   var_connection = sqlite3.connect("linux_database.db")

   #Now we create the cursor for access
   var_cursor = var_connection.cursor()

   var_data = [
                 ('Gentoo', '2010', 'rolling'),
                 ('Arch', '2010', 'rolling'),
                 ('Slackware', '13.0', 'fixed'),
                 ('Fedora', '12.0', 'fixed'),
                 ('Debian', '5.0', 'fixed'),
                 ('Ubuntu', '9.10', 'fixed'),
                 ('openSUSE', '11.3', 'fixed'),
                 ('Mandriva', '2010', 'fixed'),
                 ('Mint', '8.0', 'fixed'),
                 ('PCLinuxOS', '2010', 'rolling'),
               ]
 
   var_cursor.executemany('''INSERT INTO 
                          linux_table(distro, 
                          version,type) 
                          VALUES(?, ?, ?)''', var_data)

   var_connection.commit()
   var_connection.close()

   print ""
   print "Data has been input successfully"
   print "" 

except (ImportError, RuntimeError, TypeError, NameError):
   print ""
   print "Error inputing data"
   print ""

Again, here is the script running on my system:




This final script sends a query to the database and displays the result.

Code:
#!/usr/bin/python

import sqlite3

try:
   #Here is where we create the database
   var_connection = sqlite3.connect("linux_database.db")

   #Now we create the cursor for access
   var_cursor = var_connection.cursor()

   var_cursor.execute('''SELECT distro, 
                      version, 
                      type 
                      FROM linux_table
                      ORDER BY distro''')

   print "" 
   column_width = 15

   for column_description in var_cursor.description:
      print column_description[0].ljust(column_width) ,

   print ""
   print "-" * 45

   var_index = range(len(var_cursor.description))

   #Loop through the cursor dataset to extract data
   for row in var_cursor:
      for index in var_index:
         var_value = str(row[index])
         print var_value.ljust(column_width) ,
      print ""

   var_connection.commit()
   var_connection.close()

   print ""

except (ImportError, RuntimeError, TypeError, NameError):
   print ""
   print "Error, selecting data to be displayed"
   print ""


Here is the script output:




Some basic database functions in Python.
It's a simple into which you can build on.
Have Fun with it!! ;)
 

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)

regexorcist

New Member
Joined
Feb 1, 2010
Messages
178 (0.03/day)
Location
~/
System Name Slackware Linux
Processor yes
Motherboard yes
Cooling currently convection, but considering mineral oil
Memory sometimes fails due to too much beer
Video Card(s) ATI Radeon HD5570 series
Storage IDE
Display(s) 32" LCD TV
Case sometimes
Audio Device(s) huh? what? speak up, I can't hear you
Power Supply yes
Software Slackware running Open-Source software (it doesn't get any better)
Python GUI

Well after a few posts inthe Linux section,
I see how important a GUI is for many users,
so here is a basic Python GUI using Tkinter
(python's most popular GUI module, typically included in a python install)

Here is the script:

Code:
#!/usr/bin/python

from Tkinter import *

root = Tk()
root.title("Python GUI by regexorcist")
root.geometry("500x300+100+40")

def select_open():
   var_textbox.insert(END, "open\n")

def select_save():
   var_textbox.insert(END, "save\n")

def select_cut():
   var_textbox.insert(END, "cut\n")

def select_copy():
   var_textbox.insert(END, "copy\n")

def select_paste():
   var_textbox.insert(END, "paste\n")

def select_about():
   
   var_textbox.insert(END, "open\n")

def dialog():
   var_message = Toplevel()
   var_message.geometry("200x100+120+50")
   var_message.title("About")
   var_line1 = Label(var_message, text=" ")                                     
   var_line2 = Label(var_message, text="GUI by regexorcist")
   var_line3 = Label(var_message, text=" ")   
   var_button1 = Button(var_message, text="Close", command=var_message.destroy)
   var_line1.pack()
   var_line2.pack()
   var_line3.pack()
   var_button1.pack()

var_menubar = Menu(root)
var_file_menu = Menu(var_menubar, tearoff=0)
var_file_menu.add_command(label="Open", command=select_open)
var_file_menu.add_command(label="Save", command=select_save)
var_file_menu.add_command(label="Exit", command=root.quit)
var_menubar.add_cascade(label="File", menu=var_file_menu)

var_edit_menu = Menu(var_menubar, tearoff=0)
var_edit_menu.add_command(label="Cut", command=select_cut)
var_edit_menu.add_command(label="Copy", command=select_copy)
var_edit_menu.add_command(label="Paste", command=select_paste)
var_menubar.add_cascade(label="Edit", menu=var_edit_menu)

var_help_menu = Menu(var_menubar, tearoff=0)
var_help_menu.add_command(label="About", command=dialog)
var_menubar.add_cascade(label="Help", menu=var_help_menu)

var_textbox = Text(root, height=15, width=50, bd=5)
var_textbox.pack()

root.config(menu=var_menubar)
root.mainloop()


Here you can see me starting it from the terminal:



Here I exercise the FILE menu a bit:



Here I have already clicked save and the def select_save() has been executed.



Here I'm exercising the EDIT menu a bit:



Here I have already clicked copy and the def select_copy() has been executed.



Here I exercise the HELP menu which only has an About option
and associated dialog command which executes def dialog()



Here is the result of def dialog() and clicking close destroys the window.



From the FILE menu, I click Exit to close the application.

Very Simple Python GUI (using Tkinter)
(other GUI libraries include GTK+, wxWidgets, Qt, etc...)

I also used a very simple geometry manager... pack()
(others include grid() and place())

Hope this helps someone out ;)
 
Last edited:
Top