Tuesday, April 24, 2012

Final Conclusion

Hello Friends, This post would be the last post for this Blog.

I have covered all the basics that you need to understand for writing and reading a Python Script.

And basically we should by now know to make Object Oriented Programs, Error Handling, etc etc.

Programming Is Completely Your creativity, Its like I gave you the key to the car, and also taught you how to drive the car. Now its your decision, when, where and how you use it.

You might have some questions regarding Graphical Applications In Python, In That Case, You should look For:

1. Tkinter Python

2. WxPython

But hold on, to understand them you have to know Python well, Because GUI Application Development Is again a different vast topic.

For any Queries you may leave me a Mail At :c0d3gray@gmail.com

You can contact me at Facebook Here: Facebook Contact

GoodLuck Everyone!



You might like to visit my other blogs:
Computer Korner
SQL Injection Techniques

Thank You!

Saturday, April 21, 2012

Error Handling Part 3


Hello everyone in this post, I will discussing something more about the Error Handling, So now we should know how to Handle Error with Try and Except, and we have also seen the use of while statement to keep our program alive.

Now here is something new, we will continue with our old script, div.py, so lets open up the script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except SyntaxError:
        print "Error With Your Syntax"
    except NameError:
        print "Idiot, I dont Understand You"
    except ZeroDivisionError:
        print "Integer cannot be divided by me with Zero"
    except TypeError:
        print "Hmm...Sumthingz Fishy Here"
    except KeyboardInterrupt:
        print "Hey You aborted Me"
print "------------------------"
print "[+] EOF Script"


So this worked fine in the last, and this is fine if the script a small one like this one, what if you have a huge script where you have to handle many Errors, the length of the program would just keep increasing, so we wrap the common ones or similar ones in parenthesis under one except block, remember, we you write a script, try to make the script as small as possible, and also the code should be readable, now our modified script would be:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt):
        print "Error: Session Aborted"
print "------------------------"
print "[+] EOF Script"

So we see here that we have placed all the exceptions errors under a single except block. so this script would display "Error: Session Aborted" for every the errors. Now this is just to show you, the way you handle the errors for your script depends on the business needs or probably the behavior of your script.

Another thing to discuss in this post, assume you are writing a huge script, its not possible to type a customed error every time for every error. So we display the error that Pythons throws, but after handling the exception. Working again with the same script:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except (SyntaxError, NameError, ZeroDivisionError, TypeError, KeyboardInterrupt) as e:
        print "Error: ", e
print "------------------------"
print "[+] EOF Script"

On executing the script, we would get a short error message as to why the error occurred. Try this out.

Thats all for this post, hope it was informative.

Thank You!

Friday, April 20, 2012

Error Handling Part 2


Ok so now that we know about Try and Except, we will see something Interesting. Well we obviously will not want our program to get halt at any error, from last post we know how to handle the errors, now in this post I will show how to handle the errors and then continuing the script, thus giving you an idea of a full blown Python Script or Application.

Lets take the same script from the last post. So open up the div.py and we will modify the code as below:

import exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except SyntaxError:
    print "Error With Your Syntax"
except NameError:
    print "Idiot, I dont Understand You"
except ZeroDivisionError:
    print "Integer cannot be divided by me with Zero"
except TypeError:
    print "Hmm...Sumthingz Fishy Here"
except KeyboardInterrupt:
    print "Hey You aborted Me"

Now thats the main script, which can only handle the errors, but wont keep continuing the script, to achieve this we need a while loop with break statements. So our modified code would be as below:

import exceptions
while True:
    try:
        a = int (input("Enter First Num: "))
        b = int (input("Enter Second Num: "))
        print "Result: ", a/b
        break
    except SyntaxError:
        print "Error With Your Syntax"
    except NameError:
        print "Idiot, I dont Understand You"
    except ZeroDivisionError:
        print "Integer cannot be divided by me with Zero"
    except TypeError:
        print "Hmm...Sumthingz Fishy Here"
    except KeyboardInterrupt:
        print "Hey You aborted Me"
print "------------------------"
print "[+] EOF Script"

On executing the script:

>>>
Enter First Num:
Error With Your Syntax
Enter First Num: str
Hmm...Sumthingz Fishy Here
Enter First Num:
Hey You aborted Me
Enter First Num: 40
Enter Second Num: 0
Result:  Integer cannot be divided by me with Zero
Enter First Num: lol
Idiot, I dont Understand You
Enter First Num: 40
Enter Second Num: 2
Result:  20
------------------------
[+] EOF Script
>>>

So let me explain the script, I have kept the main try and except blocks inside a While loop, and the condition says, while True, means keep doing it, until you find a break statement, A break statement exits a loop. And inside the try block I have placed the break statement, so that the loop can exit only if the try is a success, if its not a success and if there is any error, it goes to the except statement, and since the except statements doesn't have a break statement, the script would loop again because of the while True condition. True is a builtin keyword. You can also replace True with 1. So it also be coded as

while 1:
     #scripts
This would give the same result. I prefer typing True, because it looks more Pythonist.

Okay, so I guess this post should be an interesting one. Hope you are learning Python from the blog. Keep Practicing, and don't forget to check my next post.

Thank You!

Thursday, April 19, 2012

Error Handling Part 1


Hello Everyone, in this post, I will discuss, about handling Error In Python. Well as a programmer, we want our script or application to run absolutely fine, without any error or warnings, making the program halt due to the error.

So It is the most important part of any programming language to handle errors. So Lets see how to Handle errors, but before lets see what all error can a simple program have:

print "Division Script"
a = int (input("Enter First Num: "))
b = int (input("Enter Second Num: "))
print "Result is: ", a/b

Save this as div.py and when we execute the program, remember we are focusing on getting Errors, so we will Generate Errors.

>>>
Division Script
Enter the First Num: 10.1
Enter the Second Num: 2
Result is:  5
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: str

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
TypeError: int() argument must be a string or a number, not 'type'
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: lol

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
  File "<string>", line 1, in <module>
NameError: name 'lol' is not defined
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num: 40
Enter the Second Num: 0
Result is:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 4, in <module>
    print "Result is: ", a/b
ZeroDivisionError: integer division or modulo by zero
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
  File "<string>", line 0
   
   ^
SyntaxError: unexpected EOF while parsing
>>> ============= RESTART ===============
>>>
Division Script
Enter the First Num:

Traceback (most recent call last):
  File "C:/Python27/div1.py", line 2, in <module>
    a = int(input("Enter the First Num: "))
KeyboardInterrupt
>>>
So here we have quite a few Error, which we never looked at earlier while programming. now we will handle those errors.So we will modify our script:

import exceptions <-- Module to Handle Error and Warning Exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except SyntaxError:
    print "Error With Your Syntax"
except NameError:
    print "Idiot, I dont Understand You"
except ZeroDivisionError:
    print "Integer cannot be divided by me with Zero"
except TypeError:
    print "Hmm...Sumthingz Fishy Here"
except KeyboardInterrupt:
    print "Hey You aborted Me"

And when we execute this script, and try to generate errors, we will get the customed messages, rather than a Traceback Error.

Ok let me explain the script first, first we imported the Module, then our main script is inside the try block, try block asks Python to try something, and if it fails or generates some error, this error will be passed to the except blocks, and if a matched except block is found, it will execute the codes under that particular except block. Also note here, I am very specific about the error types because This is a small program, and the chances of Error are limited here, what I could have done is, I could have made a global except block that would have handled any error. But its actually a bad practice, to house all errors under one except statement. Just To show you, I could have done this:

import exceptions <-- Module to Handle Error and Warning Exceptions
try:
    a = int (input("Enter First Num: "))
    b = int (input("Enter Second Num: "))
    print "Result: ", a/b
except:
    print "There is Some Error"

So this would show the same error for every kind of errors, But we don't want that, okay so lets run our modified script:

>>> ============= RESTART ===============
>>>

Enter First Num: 40
Enter Second Num: 0
Result:  Integer cannot be divided by me with Zero
>>> ============= RESTART ===============
>>>
Enter First Num: str
Hmm...Sumthingz Fishy Here
>>> ============= RESTART ===============
>>>
Enter First Num: lol
Idiot, I dont Understand You
>>> ============= RESTART ===============
>>>
Enter First Num:
Hey You aborted Me
>>> ============= RESTART ===============
>>>
Enter First Num:
Error With Your Syntax
>>>

Okay, This is all in this post, will discuss more with Error Handling in the next Post. I hope this was interesting. Don't Forget to check my next post.

Thank You!

Wednesday, April 18, 2012

Network Handling Part 3


Hello Everyone, in this post I will discuss about accessing FTP Servers with Python.

To show you some examples of FTP, I will use the 'ftp.redhat.com'

Before I proceed, a small note here, till now we have seen that we import modules by typing "import modulename", well thats correct, but with this statement we are importing all the functions of the Module, even those which we are not using in the program, so its RAM consuming. there Is another way to import specifically whatever function we need from the Module by typing "from Modulename import specific_function"

>>> from ftplib import FTP
>>> ftp =FTP('ftp.redhat.com') <--creating a connection to redhat FTP server
>>> ftp.login() <--since logging in without username and password, there is no arguments passed here, if the login had to use a username and password, the statement ud have been ftp.login('username' 'password')
'230 Login successful.'
>>> d = 'redhat/linux' <--setting a directory path
>>> ftp.cwd(d) <--change the directory
'250 Directory successfully changed.'
>>> print ftp.dir() <--To see the contents of the directory
-rw-r--r--    1 ftp      ftp           131 Dec 20  2005 README
drwxr-xr-x    3 ftp      ftp          4096 Feb 21 05:44 beta
drwxr-xr-x    6 ftp      ftp          4096 Jun 14  2007 eal
drwxrwsr-x   14 ftp      ftp          4096 Jul 25  2011 enterprise
drwxr-xr-x    2 ftp      ftp          4096 Feb 12  2006 preview
drwxr-xr-x    2 ftp      ftp          4096 Dec 03  2008 rawhide
drwxrwsr-x    4 ftp      ftp          4096 Sep 26  2008 updates
None
>>> help(ftp)
[Try this out, as its a huge output, try to understand the functions of the Module]

There is another FTP library that is yet more powerful and robust, but external is the chilkat Module, you can go to http://www.chilkatsoft.com/ and have a look.

Well thats all for this Post. Keep Practicing, I hope you are enjoying them. Don't forget to check my next post.

Thank You!

Tuesday, April 17, 2012

Network Handling Part 2

Hello Everyone, Lets now continue our Journey, with few more examples of Network Handling in Python.

First I would like to introduce you to geturl() of urllib Module

Lets Open up the Python Shell

>>> import urllib
>>> site = "http://microsoft.org"
>>> find = urllib.urlopen(site)
>>> find.geturl()
'http://www.microsoft.com/en-us/default.aspx'
>>> # geturl() tell us the redirected url

Another Function that you would like to know is urlretrieve(), which saves a copy of any webpage, but the only thing is that it would not display any images when you open up the copied html doc. but the external links on the copied web page would just work fine.

>>> urllib.urlretrieve('http://www.python.org', 'C:/files/python.html')

So the above line would save a copy of the website in C:/files named python.html

So , we have seen the basics of accessing the web pages with Python, there are some more functions which I will discuss on the next post.

Hope this was Interesting, and Don't forget to check my next Post.

Thank You!

Monday, April 16, 2012

Network Handling Part 1

Hello Everyone, welcome to the next phase of Python, where now you will discuss about handling webpages and networks. Again, its not possible for me to provide you with each and every minute details, because in programming field, you yourself have to be creative. But I will provide you with the basics so that you can start with and go in the right direction.

By now I assume while you reading this post, that you are already aware of File Handling and other Functions of Python that has been discussed so far.

So lets get started.

For dealing with web based resources and networks, Modules that are most of the times handy are: urllib, urllib2, ftplib, httplib, etc etc, these are the standard Python Modules, but for dealing with heavy web based scripts you need to go out on the internet and search for Modules that satisfies your scripting needs.

Ok so let me show you a small script to access the  resources on a shared folder on a network, ofcourse you need to have the accessing rights from the host that you will run the script.

Lets open up the Python Shell 

>>> import os
>>> location = os.listdir('\\\\192.168.10.110\\share') <---connects to the location
>>> f = open('\\\\192.168.1.106\\share\\test.txt', 'w')
>>> f.write('hey there')
>>> f.close

This was a small script through which I could access the Local Shared Folder I am sure if you have been reading my posts carefully, you can modify this to be flexible and used by anyone. Notice I have hard coded here the path, so to make it flexible that user should be able to enter any path they like.
Note: Notice here that I have used four backslash, as to access the resource we use two backslash, we use another two backslash as escaping, if you do not escape it, you would run into an error.

Let me also show you another script through which you can access the raw HTML of any webpage.

import urllib, os
wn = raw_input("Website name: ")
connect = urllib.urlopen(wn) <--Creates a connection to the webpage
for lines in connect:
    print lines

I have saved it as connect.py and when I execute it,

>>>
Website name: http://www.google.com

[Output Not Pasted Here, as Its a huge Output]

>>>

Well thus far, you should now have some knowledge and idea about accessing web resources with Python. Hope this post was helpful.

Again, if you go out on internet for Modules, make sure its a trusted site, and use the Modules after reading and understanding it, well more on network handling on future posts.

Thank You!

Sunday, April 15, 2012

File Handling In Python IV

Hello everyone, this post would not be a long one, as all the basics has been discussed about file handling.

This is just a quick review of some more File Handling Module that I could not relate to the earlier posts.

Lets get started.

>>> import os
>>> os.name
'nt'
>>> import sys
>>> sys.platform <--More Defined Way To Know About a Host OS
'win32'
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> sys.winver
'2.7'
>>> sys.subversion
('CPython', '', '') <--Python is Officially known as CPython, other version is Jython.
>>> sys.api_version
1013
>>> sys.getwindowsversion()
sys.getwindowsversion(major=5, minor=1, build=2600, platform=2, service_pack='Service Pack 2')
>>> sys.getsizeof('C:/files')
29
>>>

Play around with the sys module, type help(sys.any_method_of_sys) To get a detailed report of the Functions.

Well, Some Of You now may be thinking, how to handle some other type of file like an Image File, or say pdf, well, for these, Pythons Inbuilt Library is not enough, You have to go out on the web, to search for the Modules.

Make a Note Here, Whenever You Use Modules from the web, make sure to check that the Module is coded for Python 2 series, because Python 3 has got different syntax.

1. For Images: You need to look for PIL(Python Imaging Library) Take help of Google, as I dont want to spoon feed for everything.

2. MS Office: You need a Module named pywin32, or Python Office(especially meant for excel worksheets)

3. PDF: You need a Module named gfx, found under swftools

And a lot more are there, remember, Python is kinda open source, where codes are developed by any one and everyone. But before using any Module, make sure You use a Module from a trusted site, one good source is stackoverflow.

Now, do you remember I said when we create our own Modules we save it in places where Python looks for, one place i mentioned was Pythons root folder. There is one place and recommended as a standard Pythonist, you should always save the modules in site-packages. Example in my case its:

C:\Python27\Lib\site-packages, to verify, on the Python Shell, click on File>>Path Browser>>Expand the [+] C:\Python27\Lib\site-packages, and you should be able to see any new module that you import there.

Okay, so this was pretty much that you need to fire up your Python Instinct, hope this was helpful, Keep Practicing.

Don't forget to check my next post.

Thank You!

Saturday, April 14, 2012

File Handling In Python III

Hello everyone, in this post we will discuss more about File Handling with Python..

Okay, so far I have discussed, how to create, append, read and close a File, also discussed about how to check the current directory and change directory, how to make new folder, etc.

In this post, lets start by showing you how to delete a folder and continue with few more functions.

Lets fire up the Python Shell..

>>> os.getcwd()
'C:\\Python27'
>>> os.chdir('C:\\files')
>>> os.listdir(os.curdir)
['i m siiting here.jpg', 'Looping with disctionary.txt', 'morefiles', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sub', 'test.html', 'test1.html', 'tkinter1.pdf', 'whiskey.html']
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test.html
test1.html
tkinter1.pdf
whiskey.html
>>> # Now lets say I want to delete the test.html file
>>> os.remove('test.html') <--- Deletes a File
>>> Note: the parameter it takes is path, but since I am in the same directory, I just entered the file name, But If You want to Delete some thing on a different folder you need to type in the exact path, like C:\\folder\\subfolder\\file
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test1.html
tkinter1.pdf
whiskey.html
>>> #test.html file is missing, means it has been deleted, now lets see how to rename a file, we will rename, we will rename test1.html to sample.html
>>> os.rename('test1.html', 'sample.html')
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sample.html
sub
tkinter1.pdf
whiskey.html
>>>

We have another Function, that helps to walk through a directory, suppose u have a folder, where you have some files, and also few sub folders, where you have some more files. So os.walk() helps to recursively walk through the files. Lets check it out.

>>> path = 'C:\\files'
>>> for root, dirs, files in os.walk(path):
             print root
             print dirs
             print files
             print " "
           
C:\files
['morefiles', 'sub']
['i m siiting here.jpg', 'Looping with disctionary.txt', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sample.html', 'tkinter1.pdf', 'whiskey.html']

C:\files\morefiles
[]
['log.txt', 'myfile.txt', 'RHDSetup.log']
 
C:\files\sub
[]
['animated Pictures.txt', 'ASCII conversion Java.txt', 'average calculator 2 java.txt', 'back track wifi wpa hack.txt', 'backtrack.txt', 'backtrack2resolve.txt', 'bangladesh hackers friend.txt', 'bangladesh site hacked.txt', 'batch virus.txt', 'botnet.txt', 'CBT Sites.txt', 'CEH Linux commands.txt', 'CEHv7.txt', 'check how many times a character appears in word_java.txt', 'computer korner post.txt', 'constructor explained by Onty.txt', 'convertRHELtoCentos.txt', 'cpp keyloger.txt', 'crackinf for this software.txt', 'Cracking tut.txt', 'davemate2bhacked.txt', 'Deface and Shell.txt', 'defacepageCreator.txt', 'DummiesJava.txt', 'facebook emo added.txt', 'FootprintingCEH.txt', 'forum.txt', 'good site.txt', 'hack note.txt', 'hackers shell tool.txt']

 >>> #So what I asked Python is, please look for all the files in the folder named files under C: and display the path, display sub folders and then display the files.

 Yet Another Module, that I would like to present here, is the glob Module, that helps to display files matching a Pattern or regular expression. Lets check it out.

 >>> import glob
 >>> for files in glob.glob('C:\\files\\*.txt'):
             print files

   
C:\files\Looping with disctionary.txt
C:\files\Python post march20.txt
C:\files\Python Post March21.txt
C:\files\Python Post March22.txt
C:\files\Python Post March25.txt
C:\files\python post19th.txt
C:\files\Python27march.txt
>>> for files in glob.glob('C:\\files\\*.pdf'):
             print files

   
C:\files\tkinter1.pdf
>>> for files in glob.glob('C:\\files\\*.jpg'):
             print files

   
C:\files\i m siiting here.jpg
>>>

So you see that you can almost do anything and everything with Python, If you know Him well. Well I guess this was informative and Interesting and one of the important chapters in Python, So practice it well, and Don't Forget to check my next post.

Thank You.

Thursday, April 12, 2012

File Handling In Python II

Hello, everyone in this post, I will discuss the some more features of File Handling in Python, the very basics that you would need for handling and playing around with files in host operating system.

From the last post, we know how to create, append and read a text file in the root directory that is the C Drive of a Windows Operating system. Now what if we want to make a directory or probably create a text file somewhere else, but not in the C Drive.

So in this post, I will focus on how to jump around folders and directories.

For this we need to import a Module, named OS which is built into Python.

 >>> import os
>>> os.getcwd() <-- Returns the current working folder
'C:\\Python27'
>>> os.curdir <-- Returns the current working Drive or directory
'.'
>>> os.name <-- Returns the platform of a host Operating system.
'nt'
>>> os.mkdir('C:/PyProg') <-- Creates a New Folder
>>> os.mkdir('C:/PyProg/My_Project') <-- Creates a New Folder
>>> os.getcwd()
'C:\\Python27'
>>> os.chdir('C:/PyProg/My_Project') <--- Changes Directory
>>> os.getcwd() <-- Just a Proof, That The current Working Directory is different
'C:\\PyProg\\My_Project'
>>> os.environ <--- Returns the Environment Variables Of the Host OS.
[Try it out yourself, I am not showing the Output here, For some reason]
>>> os.listdir('C:/') <-- Directory Listing Of a Drive Or a Folder
['.rnd', 'ArrayDemo1.java', 'AUTOEXEC.BAT', 'boot.ini', 'Config.Msi', 'CONFIG.SYS', 'copy', 'dir1', 'Documents and Settings', 'files', 'Hacked.html', 'hacked.txt', 'Havij1.14Free.exe', 'Inetpub', 'Intel', 'IO.SYS', 'Java', 'log.txt', 'MSDOS.SYS', 'MSOCache', 'My Web Sites', 'NETCAT', 'NTDETECT.COM', 'ntldr', 'pagefile.sys', 'php', 'Program Files', 'pyinstaller', 'PyProg', 'Python27', 'pytoexe', 'RECYCLER', 'RHDSetup.log', 'ruby', 'streams.exe', 'System Volume Information', 'TC', 'Tc.exe', 'Tc.r00', 'Tc.r01', 'tests', 'themole-0.2.6', 'Visual Python', 'wamp', 'webgrabber', 'wget.exe', 'WINDOWS']
>>> os.getcwd()
'C:\\PyProg\\My_Project'
>>> myFile = open('Pythontext.txt', 'w')
>>> myFile.write(''' Hey, This are just the basics to show you how to use the OS Module with few examples.
If You want to Dive Deep into the Module.
Type, dir(os) in the Python Shell, To check the functions of the OS Module.
You can also type, help(os) to get a detailed report of the OS Module.
If you want to be specific about any function in the OS Module.
You need to type. help(os.function_name_of_any_OS_Module)''')
>>> myFile.close()
>>> os.getcwd()
'C:\\PyProg\\My_Project'
>>> os.listdir('C:/PyProg/My_Project')
['Pythontext.txt']
>>> myFile = open('Pythontext.txt')
>>> for lines in myFile:
                print lines

   
Hey, This are just the basics to show you how to use the OS Module with few examples.

If You want to Dive Deep into the Module.

Type, dir(os) in the Python Shell, To check the functions of the OS Module.

You can also type, help(os) to get a detailed report of the OS Module.

If you want to be specific about any function in the OS Module.

You need to type. help(os.function_name_of_any_OS_Module)
>>>
>>> myFile.close()

Well, These are the basic things that you would need very often, practice them, and Don't Forget to Check My next Post.

Thank You!

Wednesday, April 11, 2012

File Handling In Python

Hello Everyone, I guess This Post should be interesting as now we are in a position to go out of the Python Shell and touch the files of a host operating system.

In this post I will discuss about Handling File System. This is a Vast Topic where the inbuilt Python Module is not enough to get all our jobs done, but for starting point, and showing you how to use them, the inbuilt modules of Python works fine. The Word Module should not be unfamiliar with you in this post, and here onwards. And From here onwards I also assume that you know about Lists, tuples, Dictionary and all the stuffs that I posted Earlier.

Lets first start with how to create a file. So I am Going To show how to create a text file under the root directory of a Windows OS, i.e the C drive.

For a text file we should know, how to create, append, read and close a text file. We will work in the Python Shell, its same when you write a script in any text editor. Python interpreter would process and handle the scripts in same way.

The Basic Syntax for creating, appending, and reading is: variable_object_name = open('Relative Path', 'mode')

1. To create a text file named example.txt

>>> myFile = open('C:/example.txt', 'w') <--w means we want to write or create a text file
>>> myFile.write('This is the First Line\n')
>>> myFile.write('This is the second Line\n')
>>> myFile.writelines(''' This is blah blah blah......
....
...
....
This is the End of the Text file.\n''')
>>> myFile.close()

So first we have created a file in writing mode, and have written some lines, and finally closed the file.
write --> To write Lines in a text file line by line or as a paragraph
writelines --> To write a bunch of lines or paragraphs or to write a List we use writelines.

>>> sample = ['Python', 'Learning', 'is', 'Fun']
>>> myFile = open('C:/example.txt', 'a') <-- a means we want to append to the file
>>> myFile.writelines(sample)
>>> myFile.close()
>>>

2. To read the example.txt file

>>> myFile = open('C:/example.txt', 'r') <-- r means we want to read the file
>>> #By default, if we do not type the mode, python assumes it to be in read mode.
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.seek(0)
>>> #seek(position) takes the python cursor to where-ever we want, since I will show some more read Functions, i have taken the cursor to the starting position.
>>> myFile.readline()
'This is the First Line\n'
>>> myFile.readline()
'This is the second Line\n'
>>> myFile.readline()
' This is blah blah blah......\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'...\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'This is the End of the Text file.\n'
>>> myFile.readline()
'PythonLearningisFun'
>>> myFile.readline()
''
>>> #readline --> reads line by line
>>> >>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n', 'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> #readlines almost similar to read the difference is, it returns a List
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.readlines()
[]
>>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n',
'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> myFile.close()
>>>

To get a display in a readable manner, we use the For Iterator,

>>> myFile = open('C:/example.txt', 'r')
>>> for lines in myFile.readlines():
              print lines

   
This is the First Line

This is the second Line

 This is blah blah blah......

....

...

....

This is the End of the Text file.

PythonLearningisFun
>>> myFile.close()

Note: It is important to close a file, when you open it for any reason.

Now If You look in the C: Drive, you would see an example.txt file created.

Hope this was interesting, Practice it, play around with the functions, and Don't forget to check my next post.

Thank You.

Tuesday, April 10, 2012

More On Modules

Hello Everyone, in this post, I Will Discuss something more about Modules, its very interesting, so lets get started.

So far we know what a Module is and how to use them. But as We know that Modules are created by Python Users, for some specific outputs or results. Well If I make a Module and use it in my programs, I am aware of the functions in that Module. But if I use a Module created by someone else or rather the Python Builtin Modules, how am I supposed to know what are the functions of the Modules. And what does the Module do.

Well lets create a Module and try to understand with the example. The Same applies for any other Module that you will come across in Your Python Life.

Lets create a Module:

#SimpleMath Module
def __doc__():
    print "This is a simple Math Module Which Can Add Or Subtract"
def add(x,y):
    z = x + y
    return z
def sub(x,y):
    z = x - y
    return z

Save it as simplemath.py under C:/python27

Now On the Python Shell, what can you to do understand the Module,

>>> import simplemath
>>> #First we need to import the Module and then proceed
>>> dir(simplemath)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'add', 'sub']
>>> #dir(modulename) --> Lists the functions and variable name used in the Module
>>> help(simplemath)
Help on module simplemath:

NAME
    simplemath - #SimpleMath Module

FILE
    c:\python27\simplemath.py

FUNCTIONS
    add(x, y)
   
    sub(x, y)


>>> #help(modulename) - returns a detailed report of the Module
>>> help(simplemath.add)
Help on function add in module simplemath:

add(x, y)

>>> #help(modulename.functionname) -->displays the specific report of the function
>>> simplemath.__doc__()
This is a simple Math Module Which Can Add Or Subtract
>>> #modulename.__doc__() --> found on almost all standard Module, which returns a short description about what the Module does.

Well This was just a simple Module that I created for explanation, there exists a Huge Library Of Modules. And to understand any Module these steps helps every-time.

Few Builtin Modules that you would Like To Practice with are: math, urllib, urllib2, system, etc

Check them out, and try to understand them as Modules are used heavily in Python Scripts.

Thank You and Don't Forget to check My Next Post.

Monday, April 9, 2012

Importing Modules

Hello everyone, in this post I will discuss about Modules and how to import Modules.

What are Modules?

Modules are functions created by people that displays a certain output when imported.

Ok so far we know how to make a Class and Functions and how to use them, that's good, but the problem is once the Python window is closed, we cannot use the Functions created in a program for a different Program.

So here comes Modules, we make Modules and save it in places where Python looks for when we import the Module, Pythons root directory is one of the location where it searches for modules. So with this technique, we can use a Module with as many different programs we want.

Lets check this small example.

Open the IDLE, and the IDLE text editor by pressing Ctrl+n

#Sample Module
def test():
    print "I am a Sample Module"

And now save it as sample.py directly in the Python27 Directory(C:\Python27) and close the editor. So what we saved is a Module, and the name of the Module is sample, and this module has a test function that prints "I am a Sample Module"

Now on the IDLE

>>> import sample <--- Module Imported
>>> sample1.test()
I am a Sample Module
>>>

Now even if we restart the Python Shell or make a new Program, and if we Import the sample module, and call the test function, we would get the same output.

Hope this makes the Basics clear about the Modules. Now lets make a small Program That would import add, subtract modules in any program.

For this we need to make two Modules, Add and Subtract, and to be very basic lets say these modules works with two numbers. So here we Go.

1.

#The Add Module which finds the addition of two numbers
def add(x,y):
    z = x + y
    return z

Save it as add.py, so the module name is add

2.

#Module for Subtraction
def sub(x,y):
    z = x - y
    return z

Save it as sub.py, so the module name is sub

Now that we have created two modules we can use them with any programs, below is an example program

3.

#This is a Program where we import modules and work
import add
import sub
#Note if we are importing more than one module, we usually write them in one statement, separating them with a comma, so we can rewrite this as import add, sub
choice = input("Enter 1 for add, 2 for subtract: ")
x = input("Enter the First Number: ")
y = input("Enter the Second Number: ")
if choice==1:
    r = add.add(x,y)
    print "The Addition of ", x, " and ",y, " is ",r
else:
    r = sub.sub(x,y)
    print "The Subtraction of ", x, " and ",y, " is ",r
raw_input("Press Enter To Exit")

Outputs:

>>>
Enter 1 for add, 2 for subtract: 1
Enter the First Number: 23
Enter the Second Number: 43
The Addition of  23  and  43  is  66
Press Enter To Exit
>>>=========== RESTART ==============
>>>
Enter 1 for add, 2 for subtract: 2
Enter the First Number: 40
Enter the Second Number: 20
The Subtraction of  40  and  20  is  20
Press Enter To Exit
>>>

Okay so I Hope this should make the things clear about what a Module is, and how to work with it.

Practice it, as this is one of the main concept used in Python scriptings.

Thank You and Don't Forget to check the next post.

Sunday, April 8, 2012

Constructors

Hello everyone, in this post I will discuss something about Class.

So far, we know almost the basics of how to use a Class and how to make an object and how to use them.

But most of the time, it is required to do something automatically, as soon as the object is created, We will go in details about the usage in our later posts, as of now, we have to know how to make it and remember it, so that when we use it in making scripts we don't get confused.

This is the concept of an inbuilt python method known as constructor. So when a constructor method is created inside a class, and then when an object is created to use the class, Python looks if there is any constructor in the class, if it finds one, it automatically executes the constructor.

NOTE: This is the difference, previously when we used a method, we had to call the method from the class with a DOT Operator. But for a Constructor, we don't have to do so, as it automatically executes the constructor.


The built method for defining a Constructor is: def __init__(self): [Anything in this method is automatically executed and its a double underscore

Lets check a small example:

>>> class Test:
            var = "This is just a Variable"
            def __init__(self):
                     print "I Got executed even before I was called"
            def callMe(self):
                     print "I Am Lazy, You have to Call Me to See Me"

       
>>> ObjectTest = Test()
I Got executed even before I was called
>>> ObjectTest.var
'This is just a Variable'
>>> ObjectTest.callMe()
I Am Lazy, You have to Call Me to See Me
>>>

So I Hope Makes Everything Clear about what A Constructor is.

Practice it, and Don't forget to check my next Post.

Thank You.

Saturday, April 7, 2012

Overwrite Arguments of a Parent Class

Hello Everyone, In this Post I will Discuss how to overwrite the Variables or Arguments of a Parent Class when inherited.

From the earlier posts we already know how to make Classes, and how to Inherit a Parent Class.

Many a time, we inherit a Parent Class but we don't want some variables to be same as the parent class. So in this case we overwrite the variable. But the variable of the Parent Class remains unaffected.

Lets check out this simple example:

>>> class parentClass:
               car1 = "I am Mercedez Benz"
               car2 = "I am Maruti 800"
               car3 = "I am Honda City"

   

>>> class localDealer(parentClass): <--Parent Class Inherited
               car1 = "I am a Swift"  <--variable overwritten
               car3 = "I am a Zen"  <--variable overwritten
               car4 = "I am somecar" <-- A new variable created for the child class

   
>>> headDealer = parentClass() <--Object Created To use the Parent Class
>>> localCarDealer = localDealer() <-- Object Created to Use the Child Class
>>> localCarDealer.car1
'I am a Swift'
>>> localCarDealer.car2
'I am Maruti 800'
>>> localCarDealer.car3
'I am a Zen'
>>> localCarDealer.car4
'I am somecar'
>>> headDealer.car1
'I am Mercedez Benz'
>>> headDealer.car2
'I am Maruti 800'
>>> headDealer.car3
'I am Honda City'
>>>

So this was a Basic Stuff about the Overwriting variables of a Class. Practice it, and Dont Forget to check My next Post.

Thank You!

Friday, April 6, 2012

Inheriting Multiple Parent Class

Hello Everyone, This is a short post on how to inherit multiple Parent Class to a Child Class.

So far, we know how to inherit single Parent Class, So Another Important Thing You should know is how to add multiple Parent Class.

Lets check the example:

>>> class parentCar:
              car1 = "I am Car1"
              car2 = "I am Car2"
              car3 = "I am Car3"

   
>>> class parentBike:
              bike1 = "I am Bike1"
              bike2 = "I am Bike2"
              bike3 = "I am Bike3"

   
>>> class childTransport(parentCar, parentBike): <--Parent Class Inherited
              car4 = "I am Car4"
              bike4 = "I am Bike4"

   
>>>
>>> transport = childTransport() <--Object Created To use the Child Class
>>> transport.car1
'I am Car1'
>>> transport.car3
'I am Car3'
>>> transport.car4
'I am Car4'
>>> transport.bike1
'I am Bike1'
>>> transport.bike3
'I am Bike3'
>>> transport.bike4
'I am Bike4'
>>>

I hope this is pretty much self explanatory, you just need to remember this, as it helps a lot while scripting.

Thank You and Dont Forget to check my Next Post.

Thursday, April 5, 2012

Parent Class and Child Class

Hello Everyone, In this post I will discuss about the Parent Class and Child Class.

From earlier posts we already know how to make a class, and use the class by creating objects. That is good but how would you feel when you have to make several class, that are almost similar to each other. That would be a pain to type same codes and statements again and again, isn't it??

Here comes the concept of Parent Class and Child Class or also known as Super Class and Sub Class.

In this concept, we make a Parent class, and the Child Class inherits the attributes or characteristics of the Parent Class.

How do we do that? Lets check with an example:

>>> class autoMobileParent:
               car1 = "This is Maruti 800"
               car2 = "This is Mercedez Benz"
               bike1 = "This is Bajaj Pulsar"
               bike2 = "This is Harley Davidson"

   
>>> autoMobileParent.car1
'This is Maruti 800'
>>> autoMobileParent.car2
'This is Mercedez Benz'
>>> autoMobileParent.bike1
'This is Bajaj Pulsar'
>>>

Okay we have created a Parent Class, now we will make Child Class and make Make Some Objects.

>>> class childCar(autoMobileParent):  <--Here we inherited the Parent Class
                  car3 = "This is a Van"

   
>>> car = childCar()
>>> car.car1
'This is Maruti 800'
>>> car.car2
'This is Mercedez Benz'
>>> car.car3
'This is a Van'
>>>

>>> class childBike(autoMobileParent):  <--<--Here we inherited the Parent Class
               bike3 = "This is Royal Enfield"

Lets make another, just for fun..
  
>>> bike = childBike()
>>> bike.bike1
'This is Bajaj Pulsar'
>>> bike.bike2
'This is Harley Davidson'
>>> bike.bike3
'This is Royal Enfield'
>>>

Notice here, that even if we did not create car1, car2 or bike1, bike2 for the respective child class, they inherited it from the Parent Class.

Okay so I hope Super Class and Sub Class should be clear with you now, practice it, and Don't forget to check my next post.

Thank You!

Wednesday, April 4, 2012

Class and Methods

Hello Everyone, in this post I will discussing about the Classes used in OOP In some more details.

From the last post, we already know how a class looks like and what all we can have in a Class, like Methods, Arguments.

So lets create a Class and then I will explain what happens, and Remember that a Class is a Blueprint, that should have the capability to be used with multiple objects, so our class has to be flexible.

>>> class area:
            def sq(self, l,b):
                  self.l = l
                  self.b = b
                  area = self.l*self.b
                  return area
>>>

So the first line is the class header, and the name of the class is area. Second line we have defined a method name sq which takes 2 arguments l and b.

Hold on , Hold on, I see here three arguments self, l and b, so how do you say it takes 2 arguments, You must be thinking this isn't it??

Ok the mystery reveals, self is a kind of temporary variable that hold the object name that will be used with the class, remember I said that the code has to be flexible. so (self, l, b) here means (objectname, l and b) so we have made the method dynamic as it can use any object and relate to it.

Next line we have self.l = l, which means objectname.l = l of the objectname(We are letting Python know that l means the l of the objectname) and same is for the next line too.

Next we have the formula, which calculates the area by self.l*self.b(which means l of the object*b of the object) and assigns it to a variable area.

Finally we have the return statement which returns the value of the area.

Now how do we use the class? To use the class, we have to create objects, so lets make 2 objects, one for square and one for rectangle.

>>> square = area()
>>> # we have create an object named square
>>> square.sq(10,10)
100
>>> # we call the method of the object with the DOT(.) operator, object.method, in this case square.sq(10, 10) by passed the value of l and b
>>> # self.l = 10, and self.b = 10 and after calculating the area it returned the value
>>> # as i said self.l means objectname.l, so if we now try square.l it should return the value 10
>>> square.l
10
>>> # You see, it returned 10, now if we use another object, what would happen, will these values of square object change? No, it wont, because, our self argument helps to keep them separate.
>>> rect = area()
>>> rect.sq(15, 25)
375
>>> square.l
10
>>> rect.l
15
>>>
>>> square.b
10
>>> rect.b
25
>>>

And We can create as many objects we want using one class.

NOTE: Again self, is important in class, otherwise its useless, the whole purpose of class gets void, so whenever we have a method in a class, the argument self is a must, even if it does not take any argument.

An example:

>>> class example:
              def p(self):
                          print "You see its must"

       
>>> test = example()
>>> test.p()
You see its must
>>>

So I hope This Makes the concept clear, Practice It Well, Try To Understand them properly, as slowly we are diving down into Python,

Thank You!

Tuesday, April 3, 2012

OOP in Python


Hello Friends, in this post I will be discussing about Object Oriented Programming in Python.

Its very interesting, as well as very important, so pay attention and try to understand the things clearly.

Lets try to understand with the way Microsoft Word works, we have some per-defined templates in MS-Word right?? And we import one of the template, according to our choice and need, and work on it, but while doing this, are we making any changes to the template?? We create an instance of the template where we work and save the document, and this document has the characteristics of the template that we used, but the original template remains unaffected during the whole process.

Similarly, the same concept goes for Object Oriented Programming in Python, where we create an instance of a Class, and work on it.Say like, we have a program, where we have to find out the area of a square and a rectangle. well we can obviously create two separate functions for finding out the area for each. The work would be much easier, if we have the format (Length*Breadth) and we just import it and find out the area for each, isn't it?

From the things we learnt so far, what we can do is this..

>>> def area(lent, br):
           f = lent*br
           return f

>>> print "Area of rectangle is: ", area(length, breadth)
Area of rectangle is:  200
>>> l = 10
>>> b = 10
>>> print "Area of square is: ", area(l, b)
Area of square is:  100
>>> def area(lent=0, br=0):
           f = lent*br
           return f

>>> print "Area of square is: ", area()
Area of square is:  0
>>>

Notice here, how it worked, the function has been defined once, and it worked well, for both square and rectangle. So it was like a blue print or format that has been used and we used functions to make it, and this way of programming is known as Procedural Programming.

Now lets get into OOP,

In Object Oriented Programming(OOP), first of all we have to make something called Class, and this Class may contain data, or methods(think of methods as functions, the only difference is, they are called methods when they are used inside a class). And now after making the class, we can make objects out of it, seems like confusing isn't it? Don't worry, stick to the basics, gradually with future posts all the confusions will be sorted out.

Lets check this example, first we are going to make a class.

>>> class Girl:
           name = " "
           eyes = " "
           hairs = " "
           a = " "
           def SheSays(self):
                print "I Love you Everytime"

>>>

Okay, funny haa?? anyways I think this should make the basics clear...

Note: the method defined inside the class has an argument named self, it means no arguments has to be passed to get the statements inside the method. And all methods in a class should have an argument named self, its a must. We will come to know why and in more details in our future posts.

What we did is, we made a class named Girl, the attributes of class Girl are name, eyes, hairs, a, and we also have a method inside the class, which would print "She says I Love you Everytime" when the method is called.

Ok, so now that we have defined a class, we need to create an Object which would inherit the properties of the class Girl. So how do we define the object? Simple. We define a variable, and assign it to the class name

>>> MyFirstGirl = Girl()

After we have created the Object MyFirstGirl, we can create an instance of the class, and how do we do that?? By using the DOT(.) separator for each attributes or methods inside the class.

>>> MyFirstGirl.name = "Ashley"
>>> MyFirstGirl.eyes = "Brown"
>>> MyFirstGirl.hairs = "Medium"

Now we have set the attributes to the Object MyFirstGirl, and when we call them with their attributes name, it returns the value.

>>> MyFirstGirl.name
'Ashley'
>>> MyFirstGirl.eyes
'Brown'
>>> MyFirstGirl.hairs
'Medium'
>>> MyFirstGirl.SheSays()
I Love you Everytime

We can reuse the same class Girl again to define another object, lets say MySecondGirl, and set values to the attributes.

>>> MySecondGirl = Girl()
>>> MySecondGirl.name = "Diana"
>>> MySecondGirl.eyes = "Blue"
>>> MySecondGirl.hairs = "long"
>>> MySecondGirl.a = "Attractive"
>>> MySecondGirl.name
'Diana'
>>> MySecondGirl.eyes
'Blue'
>>> MySecondGirl.hairs
'long'
>>> MySecondGirl.a
'Attractive'
>>> MySecondGirl.SheSays()
I Love you Everytime
>>>

Notice that, the First object created with the same class is still the same and unchanged, and also the main class is uneffected. Let try to call the first object and see.

>>> MyFirstGirl.name
'Ashley'
>>> MySecondGirl.name
'Diana'
>>>

So isn't it Interesting?? A Class Created Once, can be used with several Objects.

Here is a short example to cover up the post in a nutshell.

>>> class area:
           l = " "
           b = " "
           r = " "

   
>>> Square = area()
>>> Square.l = 20
>>> Square.b = 20
>>> print "Area of the Square is: ", Square.l*Square.b
Area of the Square is:  400
>>>
>>> Rectangle = area()
>>> Rectangle.l = 30
>>> Rectangle.b = 50
>>> print "Area of the Rectangle is: ", Rectangle.l*Rectangle.b
Area of the Rectangle is:  1500
>>>
>>> pi = 3.14
>>> Circle = area()
>>> Circle.r = 15
>>> print "Area of the Circle is: ", pi*(Circle.r*Circle.r)
Area of the Circle is:  706.5
>>>

Okay So, I hope This was fun, and you have understood the basics of how things works in OOP.

Practice it, make your own programs.

Thank You, and Don't Forget to check My next Post.