How to download a image in a webpage in python

Hi..to all ..today i learnt how to download a image in a webpage in python…here the code is..

we need to copy the url of the image and give that in our code ..

#! usr/bin/python
import urllib2
import webbrowser
import os
# find yourself a picture on a web page you like
# (right click on the picture, look under properties and copy the address)
picture_page=”http://1.bp.blogspot.com/-_l6saamIXzk/T1hikYw-bUI/AAAAAAAAD7I/073fMnOIcwQ/s640/bhavana-stills-86-473×500.jpg”# give the url of the image to download
#webbrowser.open(picture_page) # test
# open the web page picture and read it into a variable
opener1 = urllib2.build_opener()
page1 = opener1.open(picture_page)
my_picture = page1.read()
# open file for binary write and save picture
# picture_page[-4:] extracts extension eg. .gif
# (most image file extensions have three letters, otherwise modify)
filename = “my_image” + picture_page[-4:]
print filename # test
fout = open(filename, “wb”)
fout.write(my_picture)
fout.close()
# was it saved correctly?
# test it out …
webbrowser.open(filename)
# or …
# on Windows this will display the image in the default viewer
#os.startfile(filename)

Run the file by Python filename.py

output:

Thats it…Thanks…..:)

How to extract a web page in python

Hi..to all today i learnt have to extract a webpage in python …here is the simple code…it’s so easy.. we need to install the following..

$ sudo apt-get install python-setuptools
$ sudo easy_install stripogram

import urllib
from stripogram import html2text
myurl=urllib.urlopen(“https://tuxbalaji.wordpress.com”)
html_string=myurl.read()
text= html2text( html_string )
print(text)

This is will print the source page of the given url as text as our output..

Thanks…enjoy coding in python….:)

Small game in python

Hi..today i found in a site a small guessing game in python..

here the game codes

 

Guess.py

  1. # This is a guess the number game.
  2. import random
  3. guessesTaken = 0
  4. print(‘Hello! What is your name?’)
  5. myName = input()
  6. number = random.randint(1, 20)
  7. print(‘Well, ‘ + myName + ‘, I am thinking of a number between 1 and 20.’)
  8. while guessesTaken < 6:
  9.     print(‘Take a guess.’) # There are four spaces in front of print.
  10.     guess = input()
  11.     guess = int(guess)
  12.     guessesTaken = guessesTaken + 1
  13.     if guess < number:
  14.         print(‘Your guess is too low.’) # There are eight spaces in front of print.
  15.     if guess > number:
  16.         print(‘Your guess is too high.’)
  17.     if guess == number:
  18.         break
  19. if guess == number:
  20.     guessesTaken = str(guessesTaken)
  21.     print(‘Good job, ‘ + myName + ‘! You guessed my number in ‘ + guessesTaken + ‘ guesses!’)
  22. if guess != number:
  23.     number = str(number)
  24.     print(‘Nope. The number I was thinking of was ‘ + number)

 

 

run the file by python Guess.py

its nice to learn python by playing with small games like this..

How to Connect MySQL database with Python

Hi…to all today i’m going to tell how to connect python with Mysql

we need a package named MySQLdb

install that package inorder to connect mysql and python.

$ sudo apt-get install python-mysqldb

Here is the code to connect to mysql

# !usr/bin/python
import MySQLdb
#creating connection using Mysqldb and mqsql dbname,username and password
con = MySQLdb.connect(host = “localhost”, user = “root”, passwd = “”, db = “balaji”)
#creating currsor to access to db
cursor=con.cursor()
#Executing query using cursor
cursor.execute(“SELECT VERSION()”)
result=cursor.fetchone()
#printing the result
print result
#closing the db connection .
con.close()

Save this file with .py extension

now run the file by $ python filename.py

Thats it..enjoy the coding with python…happy times!!!

Addressbook in Gtk and python

Hi to all..I did the addressbook in python-gtk..Database as MySql..here is the code in python.
#---------------------Importing the Modules------------------------
import pygtk
import gtk
pygtk.require("2.0")
#--------------Import the mysqldb to interface with mysql and python---------------------------
import MySQLdb
conn=MySQLdb.connect(host="localhost",user="root",passwd="password",db="balaji")
cursor=conn.cursor()
cursor.execute("create table if not exists users (user varchar(20),address varchar(50),email varchar(30),mobile varchar(12))")
#---------------Get All the Widgets in Main class --------------------------
class Address:
def __init__(self):
self.glade="Addressbook.glade"
self.builder=gtk.Builder()
self.builder.add_from_file(self.glade)
self.window1=self.builder.get_object("window1")
self.window2=self.builder.get_object("window2")
self.window3=self.builder.get_object("window3")
self.label=self.builder.get_object("label")
self.user=self.builder.get_object("entry1")
self.address=self.builder.get_object("entry2")
self.email=self.builder.get_object("entry3")
self.mobile=self.builder.get_object("entry4")
self.name=self.builder.get_object("entry5")
self.msg=self.builder.get_object("messagedialog1")
self.tree=self.builder.get_object("treeview1")
self.list=self.builder.get_object("liststore1")
self.x=0
self.clear()
dic={"on_window1_destroy":self.exit,"on_Add_clicked":self.add,"on_Ad_clicked":self.create,"on_Cancel_clicked":self.quit,
"on_search_clicked":self.search,"on_quit_clicked":self.quit,"on_submit_clicked":self.criteria,
"on_exit_clicked":self.exit,"on_okbutton_clicked":self.okay,"on_cancel_clicked":self.cancell

}
self.builder.connect_signals(dic)
self.window1.show()
#---------------Function to exit the code----------------------
def exit(self, widget, data=None):
gtk.main_quit()
def add(self,widget,data=None):
self.window1.hide()
self.window2.show()
#--------------Function to Add new User into Database--------------------
def create(self,widget,data=None):
user=self.user.get_text()
address=self.address.get_text()
email=self.email.get_text()
mobile=self.mobile.get_text()
a=len(user)
b=len(address)
c=len(email)
d=len(mobile)
if(a==0 or b==0 or c==0 or d==0):
self.x=0
self.msg.set_markup("Please enter all the fields")
self.msg.show()

else:
cursor.execute("""insert into users (user,address,email,mobile) values (%s,%s,%s,%s)""",(user,address,email,mobile))
self.x=1
self.msg.set_markup("Entered successfully")
cursor.execute("""select * from users""")
result=()
result=cursor.fetchall()
print type(result)
self.list.clear()
for row in result:
self.list.append([row[0],row[1],row[2],row[3]])
self.msg.show()
#---------------------Function for Search operation------------------
def search(self,widget,data=None):
self.window3.show()
def okay(self,wideget,data=None):
self.msg.hide()
if(self.x==1):
self.clear()
self.window1.show()
else:
self.window2.show()
def cancell(self,wideget,data=None):
self.msg.hide()
if(self.x==1):
self.clear()
self.window1.show()
else:
self.window2.show()
def clear(self):
self.user.set_text("")
self.address.set_text("")
self.email.set_text("")
self.mobile.set_text("")
def criteria(self,widget,data=None):
name=self.name.get_text()
conn=MySQLdb.connect(host="localhost",user="root",passwd="password",db="balaji")
cursor=conn.cursor()
cursor.execute("""select * from users where user=(%s)""",(name))
result=()
result=cursor.fetchall()
self.list.clear()
for row in result:
self.list.append([row[0],row[1],row[2],row[3]])
def quit(self,widget,data=None):
self.window1.show()
self.window2.hide()
self.window3.hide()
def exit(self,widget,data=None):
gtk.main_quit()
if __name__ == "__main__":
addr= Address()
gtk.main()

AddressBook in python

Hi to all…here is the code for address book in python


#!usr/bin/python

import sys
import MySQLdb
conn=MySQLdb.connect(host="localhost",user="root",passwd="password",db="balaji")
cursor=conn.cursor()
cursor.execute("create table if not exists users (name varchar(20),address varchar(50),email varchar(30),mobile varchar(12))")

def printt():
ch=int (raw_input("1.Add New 2.Search 3.Exit \n Enter Your Choice"))
while(ch!=4):

if(ch==1):
name=raw_input("Enter a Name")
address=raw_input("Enter address")
email=raw_input("enter Email address")
mobile=raw_input("enter mobile no.")
cursor.execute("""insert into users (name,address,email,mobile) values (%s,%s,%s,%s)""",(name,address,email,mobile))
option=raw_input("Add Another Record y/n")
if(option=='y'):
ch=1
else:
printt()

if(ch==2):
name1=raw_input("Enter a name to Search")
cursor.execute("""select * from users where name=(%s)""",(name1))
result=cursor.fetchall()
for row in result:
name=row[0]
address=row[1]
email=row[2]
mobile=row[3]
print " name=%s \n address=%s \n email=%s \n mobile=%s" % (name,address,email,mobile)
option=raw_input("Search Another Name (y/n)")
if(option=='y'):
ch=2
else:
printt()
if(ch==3):
sys.exit()

printt()

To generate random characters

Hi..today i learnt how to generate  the ranom charecters in python..

As per the ascii type starts with range 32 to 126. use any variable for iteration..

>>> for i in xrange(32, 127):
…    print chr(i),
...
  ! ” # $ % & ‘ ( ) * + , – . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~

if you don’t want space means start at 33.

 

string conversion

Hi..today i learnt how to convert string to code.instead for getting input from user everytime and placing into a variable...follow this... (e.x) a to z or 1 to 26 variables..

>>> vars = {}
>>> for x in xrange(26):
...  vars[x] = ''
...
>>> for x in xrange(26):
...  vars[x] = raw_input("What is %s? " % x)
...
>>> print vars

{0: ‘a’, 1: ‘b’, 2: ‘c’, 3: ‘d’, 4: ‘e’, 5: ‘f’, 6: ‘g’, 7: ‘h’, 8: ‘i’, 9: ‘j’, 10: ‘k’, 11: ‘l’, 12: ‘m’, 13: ‘n’, 14: ‘o’, 15: ‘p’, 16: ‘q’, 17: ‘r’, 18: ‘s’, 19: ‘t’, 20: ‘u’, 21: ‘v’, 22: ‘w’, 23: ‘x’, 24: ‘y’, 25: ‘z’}
>>>