Showing posts with label Object Oriented Programming in Python. Show all posts
Showing posts with label Object Oriented Programming in Python. Show all posts

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!

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 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.