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

Simple Python Scripts

Discussion in 'Programming & Webmastering' started by regexorcist, Feb 6, 2010.

  1. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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)
    [​IMG]

    MORE SCRIPTS TO COME
    Kreij and exodusprime1337 say thanks.
  2. exodusprime1337

    exodusprime1337

    Joined:
    Nov 27, 2007
    Messages:
    2,188 (0.89/day)
    Thanks Received:
    342
    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 says thanks.
  3. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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 :)
  4. Kreij

    Kreij Senior Monkey Moderator Staff Member

    Joined:
    Feb 6, 2007
    Messages:
    13,881 (5.02/day)
    Thanks Received:
    5,615
    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 says thanks.
  5. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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 ;)
  6. exodusprime1337

    exodusprime1337

    Joined:
    Nov 27, 2007
    Messages:
    2,188 (0.89/day)
    Thanks Received:
    342
    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.
  7. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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

    [​IMG]

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

    [​IMG]

    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")
    [​IMG]

    [​IMG]

    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.

    [​IMG]

    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. ;)
  8. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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:

    [​IMG]


    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:

    [​IMG]


    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:

    [​IMG]


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

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
  10. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
  11. regexorcist

    regexorcist New Member

    Joined:
    Feb 1, 2010
    Messages:
    178 (0.11/day)
    Thanks Received:
    46
    Location:
    ~/
    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:
    [​IMG]


    Here I exercise the FILE menu a bit:
    [​IMG]


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


    Here I'm exercising the EDIT menu a bit:
    [​IMG]


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


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


    Here is the result of def dialog() and clicking close destroys the window.
    [​IMG]


    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: Feb 12, 2010

Currently Active Users Viewing This Thread: 1 (0 members and 1 guest)

Share This Page