Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Programming in Python for beginners – part 4

python exception handling for beginner

  • Please log in to reply
No replies to this topic

#1 tux


    CC Regular

  • Member
  • PipPipPip
  • 29 posts
  • Programming Language:Java, Python, Visual Basic .NET, Fortran, Bash
  • Learning:C++

Posted 07 September 2012 - 08:51 AM

As I promised in previous tutorial (check here: http://forum.codecal...nners-–-part-3/) we are going to write a simple script for uploading images in Ubuntu (probably other Linux distributions can run script). If you are windows user then you can download VirtualBox and then install Linux (https://www.virtualb.../wiki/Downloads).
But, before we start let's do some examples.

Consider this simple code which takes number from user:

print "Enter number:"

What if user type string instead of number? Python will throw the following error:

ValueError: invalid literal for int() with base 10: 'Tux'

Exception is an event which occurs while application is running and interrupts the flow of application.
ValueError is exception type. When you have a piece of code which can produce an error then you can use exception handling. Using exception handling we can fix previous code:

print "Enter number:"
except ValueError:
print "No letters!"
print "Number increased by 1 is " , userInput+1

Put try at the suspicious code which can produce error. In our example it is input from user. In our code we are interested in ValueError exception which occurs when we take as input string. There are also other exception types which you can check at http://docs.python.o...ial/errors.html

Else is executed if no exception occurs. Code which must be executed and doesn't depend on the exception is placed inside finally.


your code
this is always executed

You can have except clause with no exceptions. Then it will catch all exceptions that occur during application execution. It is not a good programming practice because the programmer is not able to identify the cause of the problem. When you are writing exception handlers don't forget to add spaces.

Now when you know what is an exception and how to catch it is time for writing script.

Extending nautilus (file manager in Linux) functionality is done through scripts. Scripts are written in Bash, for more complex tasks Python or Perl is used. Scripts are located in special folder which contains all scripts. By default this folder is hidden. To show hidden files in nautilus use combination of keys Ctrl and H. Path to the folder is /home/yourUsername/.gnome2/nautilus-scripts. When the user copies scripts they are available in Nautilus context menu. New submenu Scripts in context menu will be shown:


In this tutorial we will develop Python script which will upload picture files to image hosting service called imm. This service is chosen because it doesn't contain annoying ads and has simple API. API stands for Application Programming Interface, it provides to programmer routines and tools to make application development easier. So lets check how to use API by opening http://imm.io/api/. There we can see the following piece of code:

<form action="http://imm.io/store/" method="post"
<input name="image" type="file" />
<input type="submit" />
In web development form is used to get data from surfer like name, surname, pictures... and send it to server. Form starts with line <form> and ends with </form>. Form is composed from input elements. Input name is used for referencing to the given field. Input type determines the type of field. Type “file” is button used for choosing a file while “submit” type is button used for sending data to server.
You probably asked yourself where data will be sent? It will be sent to file called store which is located at http://imm.io for processing. Method tells us how to transfer data to server. There are 2 types: GET and POST. GET is used for getting content of web page. POST is used for sending data to web page.
After we send data to server, in our case it is picture, what we can expect as output? If you check API the answer is in form of JSON. JSON is data exchange format which is human readable. For that we will use python library called json. Now when we know what our python script will do we move to writing code. Before we begin make sure you have installed library called requests (available at http://docs.python-r...nstall/#install) . Install it using the following command:
pip install requests

In case you don't have installed pip go to Ubuntu Software Center and type python-pip.
The code is shown below:

import requests
import os
import json
import gtk
siteResponse=requests.post(url, files={'image':openedFile})
# if json response contains Error uploading show it to the user
if 'error uploading' in imageUrl[u'payload']:
raise Exception(gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Error uploading!").run())
except requests.Connectionerror:
gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Check your connection!").run()
# else is executed if there is no error in application
gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Image url is "+ imageUrl[u'payload'][u'uri']).run()

First 4 lines imports libraries we need for project. Os is imported because we need it to get environment variable NAUTILUS_SCRIPT_SELECTED_FILE_PATHS which returns the path to selected file. Other enivronment variables which nautilus provides for our script are:

NAUTILUS_SCRIPT_SELECTED_FILE_PATHS: newline-delimited paths for selected files (only if local)

NAUTILUS_SCRIPT_SELECTED_URIS: newline-delimited URIs for selected files


NAUTILUS_SCRIPT_WINDOW_GEOMETRY: position and size of current window

NAUTILUS_SCRIPT_NEXT_PANE_SELECTED_FILE_PATHS: newline-delimited paths for selected files in the inactive pane of a split-view window (only if local)

NAUTILUS_SCRIPT_NEXT_PANE_SELECTED_URIS: newline-delimited URIs for selected files in the inactive pane of a split-view window

NAUTILUS_SCRIPT_NEXT_PANE_CURRENT_URI: URI for current location in the inactive pane of a split-view window
As I said json will process output from web page and convert it to python dictionary. Gtk will be used for displaying message box with url to our picture. Next lines are clear enough so there is no need to explain them. Line siteResponse=requests.post(url, files={'image':openedFile}) is used to send data to server using requests library. It takes two arguments: website where we send data and file path. File path is pointed by input element called image. After executing POST the web site returns JSON response into variable called siteResponse. In next line we use python's library JSON to convert it to dictionary so we can easily manipulate with data. If uploading picture fails JSON response will look like:

{"success":false,"payload":"error uploading"}

After converting to python dictionary it look like:

{u'payload': u'error uploading', u'success': False}

if 'error uploading' in imageUrl[u'payload']:
raise Exception(gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Error uploading!").run())
checks for value of key u'payload'. In case it contains error uploading it will show message as shown on the picture:


This error is shown when you try to upload file which is not picture. Lines
except requests.Connectionerror:
gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Check your connection!").run()
checks for connection. If connection is not available it will show message. Finally if there is no errors last line of code will print image url.


Script is attached here: Attached File  Upload image.py   924bytes   293 downloads
  • 0

Also tagged with one or more of these keywords: python exception handling, for beginner

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download