Showing posts with label python tutorial 2.7. Show all posts
Showing posts with label python tutorial 2.7. Show all posts

Wednesday, November 18, 2015

Creating Executable File from Python Script

Python executable file , the .exe extension , I must make it clear; could be created by a simple module 'pyinstaller'. To do this you must have to install pip before hand. If you don't have pip install you can do it by  clicking this link - http://pip.readthedocs.org/en/stable/installing/.

Now, after you have pip installed and working , you can install the pyinstaller with  -

pip install pyinstaller

make sure you have an internet connection functioning in a proper way i.e. without proxy.

Now suppose you have a python script from which you want to make a .exe file. I will use a basic GUI script of python for this purpose. So, my file will be something like this -

from Tkinter import *
def clickme():
    label=Label(root,text="Hello There").pack()
root=Tk()
buttton=Button(root,text="Click me",command=clickme).pack()
root.mainloop()






The name of the script is simplegui.py. To make an executable file from the script we need to run this - You need to be in same directory as the script file, so use cd command to reach there, Suppose the script is in D:\hello folder so we need to the below commands -

c:\> d:
d:\> cd hello
d:\hello>pyinstaller.exe --onefile --windowed simplegui.py


You will see a dist folder created there , and in there you can see the desired exe file. Double click to run it and enjoy your first executable python script on windows.

Tuesday, November 3, 2015

Showing a List as String in Python

In my previous example and in my website, I have shown you how to split a string and make a list out of it. We simply used the split() function of the string to do so. e.g.

>>> a="The tiny runner running through the narrow edges"
>>> a.split()
['The', 'tiny', 'runner', 'running', 'through', 'the', 'narrow', 'edges']


As you can see the split operation which can split the string and make a list from it. But what if we need to join it again to get the actual string again? Python has a join keyword for this purpose -

>>> ''.join(a)
'The tiny runner running through the narrow edges'


Now, what if we have a list which has integer variables in it. We can not simply right the above function , we need to have a lambda function. Let's have a list of integers - 

>>> a=[1,2,3,4,4,5,5] 
>>> ''.join(a)

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    ''.join(a)
TypeError: sequence item 0: expected string, int found


We can solve the problem using the lambda function, as shown below -


>>> ''.join(map(lambda a:str(a),a))
'123456'


See, the easy way to get the string back!  

Sunday, August 16, 2015

A Combination of Both Python CGI and Database Programming

Python CGI can be helpful to get data from a form and insert it into a database. So, a combination of both the CGI programming and a little bit of database programming can help us to create and maintain a small web based database. See the example below -

Lets start with creating a form. In the form action you can see that I have called a python cgi file and use th method post. Always store the CGI file in the cgi-bin folder. Then we have created a text entry for username label and another for password level. We use the submit button to call the cgi file.
It will create a form like below - 
<html>
<link rel="stylesheet" type="text/css" href="new1.css">
<head>
<title>Login Page</title>
<head>
<h1> Welcome to The Gate Pass Entry System</h1>
<h2>Please enter username and password to access the system</h2>
<body>
<form action='/cgi-bin/formvalidator.py' method='POST'>
<label>Username: </label>
<input type='text' name='username'><br><br/>
<label>Password:  </label>
<input type="Password"  name='password' ><br/><br/>
<input type='submit' value=submit>
</form>
</body>
</html>

 The Output will be something like below -


The next thing we have to do is to handle the input from the form and get data from it ;then we will insert the data to a database. Lets do it -

#!/Python27/python  (#!/usr/bin/python - in case of linux)
import cgi,cgitb
cgitb.enable() #This will show errors in the browser
data=cgi.FieldStorage() #The Fieldstorage function allow us to get data from form.
username=str(data['username'].value) #getting the value of the name='username'  field
password=str(data['password'].value) #getting the value of the name='password' field


Now the data collection part is covered up, as we can see we have two variables username and password which are holding the inputs from the HTML form. Now lets put them in database. Please visit http://pythonbeginner.in/databaseprogramming if you have not done a bit of database programming with python.We will crate a table named login_list and put the data there.

import sqlite3 as db #You should import this in the first or second line of the program.
conn=db.connect('test1.db') #Connecting to database named test1.db
cur=conn.cursor()
cur.execute('drop table if exists login_list')
cur.execute("CREATE TABLE login_list (uniqueid integer primary key AUTOINCREMENT,usernameTEXT,password TEXT);")
conn.commit()
cur.execute('insert into troublebook(username,password) values(?,?)',(username,password))
conn.commit()
So, what the program actually did? It took the variables username and password and inserted into the login_list table for storing. It is basically a table for entering username and password but not verifying it. What if we need to verify if it is in the database and if not found then insert the value in the list. 
Hint: The 'select * from table' is used to have the entire table as output. Can we use it here ? Obviously. but how, let's find out and stay tuned for the next blog entry.

Now lets traverse the list with the help of database and generate a HTML page on your browser showing all username and password. 

import sys,cgi,cgitb
import sqlite3 as db
conn=db.connect('test1.db')
query='select * from login_list'
cur.execute(query)
rows=cur.fetchall()
sys.stdout.write("Content-type: text/html\r\n\r\n")
sys.stdout.write("")
sys.stdout.write("<html><body><h1>Login List :</h1><p>")
for row in rows:
   print ("_________________________________________________________<br/>\n")
   print ("\n")

   sys.stdout.write("ID No : %s <br>Name :%s <br>Password : %s" % (row[0], row[1], row[2]))
   sys.stdout.write("<br/>")
  
sys.stdout.write("</p></body></html>")


This will list the whole login_list database and place it in your web browser with a suitable format.You can use another program or another link to run this, the main thing i the concept of the CGI must be cleared now, as we will be moving to more complex structure of the cgi programming.
  

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...