• We've upgraded our forums. Please post any issues/requests in this thread.

Simple Python Scripts

Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#1
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,228 (0.61/day)
Likes
374
System Name HOMECOMPUTER
Processor Intel I7-4790k @ 4.8Ghz 1.30v
Motherboard Gigabyte z97 gaming 7
Cooling ek supremacy evo full nickle, xspc megarad
Memory 16GB Corsair ddr3 2400
Video Card(s) Sapphire r9 Fury Tri-x @ 1200/500
Storage 2x samsung 840 evo in raid 0
Display(s) LG 35", LG 27"
Case Thermaltake Core x5
Audio Device(s) Asus xonar dsx pcie
Power Supply Corsair 1000watt
Mouse Zowie FK1+
Keyboard Corsair Strafe rgb silent
Software Windows 10 Pro
Benchmark Scores i'm working on that
#2
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?
 
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#3
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
Staff member
Joined
Feb 6, 2007
Messages
13,817 (3.49/day)
Likes
5,524
Location
Cheeseland (Wisconsin, USA)
Processor Intel Core 2 Quad QX9650 Extreme @ 3.0 GHz
Motherboard Asus Rampage Formula
Cooling ZeroTherm Nirvana NV120 Premium
Memory 8GB (4 x 2GB) Corsair Dominator PC2-8500
Video Card(s) 2 x Sapphire Radeon HD6970
Storage 2 x Seagate Barracuda 320GB in RAID 0
Display(s) Dell 3007WFP 30" LCD (2560 x 1600)
Case Thermaltake Armor w/ 250mm Side Fan
Audio Device(s) SupremeFX 8ch Audio
Power Supply Thermaltake Toughpower 750W Modular
Software Win8 Pro x64 / Cat 12.10
#4
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:
 
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#5
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,228 (0.61/day)
Likes
374
System Name HOMECOMPUTER
Processor Intel I7-4790k @ 4.8Ghz 1.30v
Motherboard Gigabyte z97 gaming 7
Cooling ek supremacy evo full nickle, xspc megarad
Memory 16GB Corsair ddr3 2400
Video Card(s) Sapphire r9 Fury Tri-x @ 1200/500
Storage 2x samsung 840 evo in raid 0
Display(s) LG 35", LG 27"
Case Thermaltake Core x5
Audio Device(s) Asus xonar dsx pcie
Power Supply Corsair 1000watt
Mouse Zowie FK1+
Keyboard Corsair Strafe rgb silent
Software Windows 10 Pro
Benchmark Scores i'm working on that
#6
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.
 
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#7
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. ;)
 
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#8
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!! ;)
 
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#9
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#10
Joined
Feb 1, 2010
Messages
178 (0.06/day)
Likes
46
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)
#11
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: