# Simple Python Scripts



## regexorcist (Feb 6, 2010)

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.

```
#!/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


----------



## exodusprime1337 (Feb 6, 2010)

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 (Feb 6, 2010)

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 
	
	



```
#!/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 (Feb 6, 2010)

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.


----------



## regexorcist (Feb 6, 2010)

Ha! Ha! Thanks for the kind words Kreij,
but I'm just a hack 

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

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


----------



## exodusprime1337 (Feb 6, 2010)

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 (Feb 6, 2010)

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) 

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

```
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.

```
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.


```
>>> 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 

Now lets do some scripting.


----------



## regexorcist (Feb 7, 2010)

*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:


```
#!/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.


```
#!/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.


```
#!/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 (Feb 9, 2010)

Now that we have a database example (see previous post)
here is a *real world* python success story.
http://www.python.org/about/success/verity/


----------



## regexorcist (Feb 10, 2010)

Here is an interesting find:
http://www.pyinstaller.org/


----------



## regexorcist (Feb 12, 2010)

*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:


```
#!/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


----------

