diff --git a/en-US/Python_for_you_and_me.xml b/en-US/Python_for_you_and_me.xml index 55939e9..f4b83b6 100644 --- a/en-US/Python_for_you_and_me.xml +++ b/en-US/Python_for_you_and_me.xml @@ -17,8 +17,9 @@ + + - diff --git a/en-US/acknowledgment.xml b/en-US/acknowledgment.xml index 1c769c5..69bbd56 100644 --- a/en-US/acknowledgment.xml +++ b/en-US/acknowledgment.xml @@ -10,15 +10,16 @@ - Jared Smith - Marco Mornati - Nicu Buculei - Paul W. Frields - Pradeepto K Bhattacharya - Sankarshan Mukhopadhyay + Jared Smith + Marco Mornati + Nicu Buculei + Paul W. Frields + Pradeepto K Bhattacharya + Prashad J. Pandit + Sankarshan Mukhopadhyay Sayamindu Dasgupta Stephanie Whiting - Prashad J. Pandit + I am missing some names in the above list, will add them soon diff --git a/en-US/classes.xml b/en-US/classes.xml index 5dc669e..2acd2a2 100644 --- a/en-US/classes.xml +++ b/en-US/classes.xml @@ -24,7 +24,7 @@ in the statements you can write any python statement, you can define functions (which we call methods of a class). ->> class MyClass: +>> class MyClass: ... a = 90 ... b = 88 ... @@ -32,14 +32,14 @@ >>> p <__main__.MyClass instance at 0xb7c8aa6c> ]]> - + In the above example you can see first we are declaring a class called MyClass, writing some random statements inside that class. After the class definition, we are creating an object p of the class MyClass.If you do a dir on that... ->> dir(p) +>> dir(p) ['__doc__', '__module__', 'a', 'b'] ]]> - + You can see the variables a and b inside it. @@ -47,47 +47,64 @@
__init__ method __init__ is a special method in python classes, it is the constructor method for a class. In the following example you can see how to use it ->> class Student: -... def __init__(self, name, branch, year): -... self.name = name -... self.branch = branch -... self.year = year -... print "A student object is created" -... def getName(self): -... return self.name -... def setName(self, name): -... self.name = name -... + - + __init__ is called when ever an object of the class is constructed.That means when ever we will create a student object we will see the message "Creating a new student" in the prompt. You can see the first argument to the method is self. It is a special variable which points to the current object (like `this` in C++). The object is passed implicitly to every method available in it , but we have to get it explicitly in every method while writing the methods. Example shown below. ->> std1 = Student() +>> std1 = Student() Traceback (most recent call last): File "", line 1, in TypeError: __init__() takes exactly 4 arguments (1 given) >>> std1 = Student('Kushal','CSE','2005') A student object is created ]]> - + In this example at first we tried to create a Student object with passing any argument and python interpreter complained that it takes exactly 4 arguments but received only one (self). Then we created an object with proper argument values and from the message printed, one can easily understand that __init__ method was called as the constructor method. Now we are going to call getName() and setName() methods. ->> std1.getName() +>> std1.get_name() 'Kushal' ->>> std1.setName() +>>> std1.set_name() Traceback (most recent call last): File "", line 1, in -TypeError: setName() takes exactly 2 arguments (1 given) ->>> std1.setName('Shreyank Gupta') ->>> std1.getName() +TypeError: set_name() takes exactly 2 arguments (1 given) +>>> std1.set_name('Shreyank Gupta') +>>> std1.get_name() 'Shreyank Gupta' ]]> - + First we called getName on the object we created, then tried to call setName without any arguments and we got an error. Next we again called setName with argument 'Shreyank Gupta'. Now calling getName gives 'Shreyank Gupta' as the output. @@ -106,40 +123,54 @@ TypeError: setName() takes exactly 2 arguments (1 given) student_teacher.py @@ -147,15 +178,15 @@ print teacher1.getDetails() The output: - - In this example you can see how we called the __init__ method of the class Person in both Studentą¦¾ and Teacher classes' __init__ method. We also reimplemented getDetails() method of Person class in both Student and Teacher class. So, when we are calling getDetails() method on the teacher1 object it returns based on the object itself (which is of teacher class) and when we call getDetails() on the student1 or person1 object it returns based on getDetails() method implemented in it's own class. + In this example you can see how we called the __init__ method of the class Person in both Student and Teacher classes' __init__ method. We also reimplemented get_details() method of Person class in both Student and Teacher class. So, when we are calling get_details() method on the teacher1 object it returns based on the object itself (which is of teacher class) and when we call get_details() on the student1 or person1 object it returns based on get_details() method implemented in it's own class.
@@ -177,14 +208,14 @@ Rahul As we already know how to create an object , now we are going to see how to delete an python object. We use del for this. ->> s = "I love you" +>> s = "I love you" >>> del s >>> s Traceback (most recent call last): File "", line 1, in NameError: name 's' is not defined ]]> - + del actually decreases reference count by one. When the reference count of an object becomes zero the garbage collector will delete that object. diff --git a/en-US/collections.xml b/en-US/collections.xml new file mode 100644 index 0000000..929ab13 --- /dev/null +++ b/en-US/collections.xml @@ -0,0 +1,98 @@ + + + + + Collections module + + In this chapter we will learn about a module called Collections. In this module we some nice data structures which will help you to solve various real life problems. + + +>> import collections]]> + + + This is how you can import the module, now we will see the available classes which you can use. + +
+ Counter + + Counter is a dict subclass which helps to count hashable objects. Inside it elements are stored as dictionary keys and counts are stored as values which can be zero or negative. + + + Below we will see one example where we will find occurrences of words in the Python LICENSE file. + + + Counter example + >> from collections import Counter +>>> import re +>>> path = '/usr/share/doc/python-2.7.3/LICENSE' +>>> words = re.findall('\w+', open(path).read().lower()) +>>> Counter(words).most_common(10) +[('2', 97), ('the', 80), ('or', 78), ('1', 76), ('of', 61), ('to', 50), ('and', 47), ('python', 46), ('psf', 44), ('in', 38)]]]> + + + + Counter objects has an method called elements which returns an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order. + + +>> c = Counter(a=4, b=2, c=0, d=-2) +>>> list(c.elements()) +['a', 'a', 'a', 'a', 'b', 'b']]]> + + + + most_common is a method which returns most common elements abd their counts from the most common to the least. + + +>> Counter('abracadabra').most_common(3) +[('a', 5), ('r', 2), ('b', 2)]]]> + +
+
+ defaultdict + + defaultdict is a dictionary like object which provides all methods provided by dictionary but takes first argument (default_factory) as default data type for the dictionary. Using defaultdict is faster than doing the same using dict.set_default method. + + + defaultdict example + +>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] +>>> d = defaultdict(list) +>>> for k, v in s: +... d[k].append(v) +... +>>> d.items() +[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]]]> + + + + In the example you can see even if the key is not there in the defaultdict object, it automatically creates an empty list. list.append then helps to append the value to the list. + +
+
+ namedtuple + + Named tuples helps to have meaning of each position in a tuple and allow us to code with better readability and self-documenting code. You can use them in any place where you are using tuples. In the example we will create a namedtuple to show hold information for points. + + + Named tuple + +>> from collections import namedtuple +>>> Point = namedtuple('Point', ['x', 'y']) #Defining the namedtuple +>>> p = Point(10, y=20) #Creating an object +>>> p +Point(x=10, y=20) +>>> p.x + p.y +30 +>>> p[0] + p[1] #Accessing the values in normal way +30 +>>> x, y = p #Unpacking the tuple +>>> x +10 +>>> y +20]]> + + +
+ +
\ No newline at end of file diff --git a/en-US/datastructure.xml b/en-US/datastructure.xml index 993138c..194d93c 100644 --- a/en-US/datastructure.xml +++ b/en-US/datastructure.xml @@ -318,7 +318,7 @@ parthan uses Ubuntu Many times it happens that we want to add more data to a value in a dictionary and if the key does not exists then we add some default value. You can do this efficiently using dict.setdefault(key, default). ->>> data = {} +>> data = {} >>> data.setdefault('names', []).append('Ruby') >>> data {'names': ['Ruby']} @@ -328,18 +328,20 @@ parthan uses Ubuntu >>> data.setdefault('names', []).append('C') >>> data {'names': ['Ruby', 'Python', 'C']} +]]> When we try to get value for a key which does not exists we get KeyError. We can use dict.get(key, default) to get a default value when they key does not exists before. - ->>> data['foo'] + +>> data['foo'] Traceback (most recent call last): File "", line 1, in KeyError: 'foo' >>> data.get('foo', 0) 0 +]]> If you want to loop through a list (or any sequence) and get iteration number at the same time you have to use enumerate(). diff --git a/en-US/file.xml b/en-US/file.xml index e934866..29b0f08 100644 --- a/en-US/file.xml +++ b/en-US/file.xml @@ -20,10 +20,10 @@ The default mode is read only, ie if you do not provide any mode it will open the file as read only. Let us open a file ->> f = open("love.txt") +>> f = open("love.txt") >>> f ]]> - +
@@ -31,11 +31,11 @@ After opening a file one should always close the opened file. We use method close() for this. ->> f = open("love.txt") +>> f = open("love.txt") >>> f >>> f.close()]]> - + Important @@ -56,37 +56,37 @@ Because To read the whole file at once use the read() method. ->> f = open("sample.txt") +>> f = open("sample.txt") >>> f.read() 'I love Python\nPradeepto loves KDE\nSankarshan loves Openoffice\n']]> - + If you call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file. ->> f = open("sample.txt") +>> f = open("sample.txt") >>> f.readline() 'I love Python\n' >>> f.readline() 'Pradeepto loves KDE\n']]> - + To read all the all the lines in a list we use readlines() method. ->> f = open("sample.txt") +>> f = open("sample.txt") >>> f.readlines() ['I love Python\n', 'Pradeepto loves KDE\n', 'Sankarshan loves Openoffice\n']]]> - + You can even loop through the lines in a file object. ->> f = open("sample.txt") +>> f = open("sample.txt") >>> for x in f: ... print x, ... I love Python Pradeepto loves KDE Sankarshan loves Openoffice]]> - + Let us write a program which will take the file name as the input from the user and show the content of the file in the console. @@ -102,7 +102,7 @@ f.close()]]> The output - Let us open a file then we will write some random text into it by using the write() method. ->> f = open("ircnicks.txt", 'w') +>> f = open("ircnicks.txt", 'w') >>> f.write('powerpork\n') >>> f.write('indrag\n') >>> f.write('mishti\n') ->>> f.write('sm|CPU') +>>> f.write('sankarshan') >>> f.close()]]> - + Now read the file we just created ->> f = open('ircnicks.txt') +>> f = open('ircnicks.txt') >>> s = f.read() >>> print s powerpork indrag mishti -sm|CPU]]> - +sankarshan]]> +
copyfile.py - In this example we will copy a given file to another file. + In this example we will copy a given text file to another file. + + + This way of reading file is not always a good idea, a file can be very large to read and fit in the memory. It is always better to read a known size of the file and wirte that to the new file. + + You can see we used a new module here sys. sys.argv contains all command line parameters. Remember cp command in shell, after cp we type first the file to be copied and then the new file name. @@ -169,13 +174,13 @@ for i, x in enumerate(sys.argv): The output - - + Here we used a new function enumerate(iterableobject), which returns the index number and the value from the iterable object. @@ -201,10 +206,10 @@ Note that not all file objects are speakable. Let us see one example ->> f = open('tempfile', 'w') +>> f = open('/tmp/tempfile', 'w') >>> f.write('0123456789abcdef') >>> f.close() ->>> f = open('tempfile') +>>> f = open('/tmp/tempfile') >>> f.tell() #tell us the offset position 0L >>> f.seek(5) # Goto 5th byte @@ -215,13 +220,68 @@ Note that not all file objects are speakable. >>> f.seek(-3, 2) # goto 3rd byte from the end >>> f.read() #Read till the end of the file 'def']]> - +
Count spaces, tabs and new lines in a file - Let us try to write an application which will count the spaces , tabs, and new lines in any given file. + Let us try to write an application which will count the spaces , tabs, and lines in any given file. + + 1: + main(sys.argv[1]) + else: + sys.exit(-1) + sys.exit(0) +]]> + + + You can see that we have two functions in the program , main and parse_file where the second one actually parses the file and returns the result and we print the result in main function. By splitting up the code in smaller units (functions) helps us to organize the codebase and also it will be easier to write test cases for the functions. +
diff --git a/en-US/functions.xml b/en-US/functions.xml index 02d2f8a..b30a2f7 100644 --- a/en-US/functions.xml +++ b/en-US/functions.xml @@ -12,23 +12,23 @@ We use def keyword to define a function. general syntax is like - - + Let us write a function which will take two integers as input and then return the sum. ->> def sum(a, b): +>> def sum(a, b): ... return a + b]]> - + In the second line with the return keyword, we are sending back the value of a + b to the caller. You must call it like ->> res = sum(234234, 34453546464) +>> res = sum(234234, 34453546464) >>> res 34453780698L]]> - + Remember the palindrome program we wrote in the last chapter. Let us write a function which will check if a given string is palindrome or not, then return True or False. @@ -69,7 +69,7 @@ change(a) print "After the function call ", a]]> The output - @@ -98,21 +98,21 @@ print "After the function call ", a]]> In a function variables may have default argument values, that means if we don't give any value for that particular variable it will assigned automatically. ->> def test(a , b = -99): +>> def test(a , b = -99): ... if a > b: ... return True ... else: ... return False ]]> - + In the above example we have written b = -99 in the function parameter list. That means of no value for b is given then b's value is -99. This is a very simple example of default arguments. You can test the code by ->> test(12, 23) +>> test(12, 23) False >>> test(12) True]]> - + Important @@ -122,7 +122,7 @@ True]]> Also remember that default value is evaluated only once, so if you have any mutable object like list it will make a difference. See the next example ->> def f(a, data=[]): +>> def f(a, data=[]): ... data.append(a) ... return data ... @@ -132,12 +132,12 @@ True]]> [1, 2] >>> print f(3) [1, 2, 3]]]> - +
Keyword arguments ->> def func(a, b=5, c=10): +>> def func(a, b=5, c=10): ... print 'a is', a, 'and b is', b, 'and c is', c ... >>> func(12, 24) @@ -146,16 +146,48 @@ a is 12 and b is 24 and c is 10 a is 12 and b is 5 and c is 24 >>> func(b=12, c = 24, a = -1) a is -1 and b is 12 and c is 24]]> - + In the above example you can see we are calling the function with variable names, like func(12, c = 24), by that we are assigning 24 to c and b is getting its default value. Also remember that you can not have without keyword based argument after a keyword based argument. like ->> def func(a, b=13, v): +>> def func(a, b=13, v): ... print a, b, v ... File "", line 1 SyntaxError: non-default argument follows default argument]]> - + +
+
+ Docstrings + + In Python we use docstrings to explain how to use the code, it will be useful in interactive mode and to create auto-documentation. Below we see an example of the docstring for a function called longest_side. + + + text + + + + + + We will learn more on docstrings in reStructuredText chapter. + +
diff --git a/en-US/looping.xml b/en-US/looping.xml index aa61504..d4ac3e0 100644 --- a/en-US/looping.xml +++ b/en-US/looping.xml @@ -13,14 +13,14 @@ The syntax for while statement is like - - + The code we want to reuse must be indented properly under the while statement. They will be executed if the condition is true. Again like in if-else statement any non zero value is true. Let us write a simple code to print numbers 0 to 10 ->> n = 0 +>> n = 0 >>> while n < 11: ... print n ... n += 1 @@ -36,7 +36,7 @@ 8 9 10]]> - + In the first line we are setting n = 0, then in the while statement the condition is n 11 , that means what ever line indented below that will execute until n becomes same or greater than 11. Inside the loop we are just printing the value of n and then increasing it by one. @@ -56,7 +56,8 @@ while b < 100: The output - + - + In the first line of the code we are initializing a and b, then looping while b's value is less than 100. Inside the loop first we are printing the value of b and then in the next line putting the value of b to a and a + b to b in the same line. @@ -85,9 +86,9 @@ while b < 100: The output - - +
Power Series @@ -107,21 +108,21 @@ while n <= 100: print "No of Times= %d and Sum= %f" % (n, sum)]]> The output - +No of Times= 7 and Sum= 1.648720]]> In this program we introduced a new keyword called break. What break does is stop the innermost loop. In this example we are using break under the if statement - - + This means if the value of term is less than 0.0001 then get out of the loop. @@ -146,7 +147,7 @@ while i < 11: print "-" * 50]]> The output - 9 18 27 36 45 54 63 72 81 90 10 20 30 40 50 60 70 80 90 100 --------------------------------------------------]]> - + Here we used one while loop inside another loop, this is known as nested looping. You can also see one interesting statement here - - + + In a print statement if we multiply the string with an integer n , the string will be printed nmany times. Some examples ->> print "*" * 10 +>> print "*" * 10 ********** >>> print "#" * 20 #################### @@ -176,7 +177,7 @@ print "-" * 50]]> ---------------------------------------- >>> print "-" * 40 ----------------------------------------]]> - +
@@ -194,14 +195,14 @@ while n >= 0: n -= 1]]> The output - - + Design 2 The output - - + Design 3 = 0: n -= 1]]> The output - - +
@@ -245,18 +246,18 @@ Enter the number of rows: 5 We are going to learn a data structure called list before we go ahead to learn more on looping. Lists an be written as a list of comma-separated values (items) between square brackets. ->> a = [ 1 , 342, 2233423, 'India', 'Fedora'] +>> a = [ 1 , 342, 2233423, 'India', 'Fedora'] >>> a [1, 342, 2233423, 'India', 'Fedora']]]> - + Lists can keep any other data inside it. It works as a sequence too, that means ->> a[0] +>> a[0] 1 >>> a[4] 'Fedora']]> - + You can even slice it into different pieces, examples are given below ->> a[4] +>> a[4] 'Fedora' >>> a[-1] 'Fedora' @@ -269,35 +270,46 @@ Enter the number of rows: 5 >>> a[:-2] [1, 342, 2233423] >>> a[0::2] -[1, 2233423, 'Fedora']]]> +[1, 2233423, 'Fedora']]]> In the last example we used two :(s) , the last value inside the third brackets indicates step. s[i:j:k] means slice of s from i to j with step k. To check if any value exists within the list or not you can do ->> a = ['Fedora', 'is', 'cool'] +>> a = ['Fedora', 'is', 'cool'] >>> 'cool' in a True >>> 'Linux' in a False]]> - + That means we can use the above statement as if clause expression. The built-in function len() can tell the length of a list. ->> len(a) +>> len(a) 3]]> - + + + + If you want to test if the list is empty or not, do it like this + +if list_name: #This means the list is not empty + pass +else: #This means the list is empty + pass + + +
For loop There is another to loop by using for statement. In python the for statement is different from the way it works in C. Here for statement iterates over the items of any sequence (a list or a string). Example given below ->> a = ['Fedora', 'is', 'powerfull'] +>> a = ['Fedora', 'is', 'powerfull'] >>> for x in a: ... print x, ... Fedora is powerfull]]> - + We can also do things like ->> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> for x in a[::2]: ... print x ... @@ -306,7 +318,7 @@ Fedora is powerfull]]> 5 7 9]]> - +
@@ -314,7 +326,7 @@ Fedora is powerfull]]> range() is a buitin function. From the help document - list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. @@ -322,18 +334,18 @@ Fedora is powerfull]]> For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. ]]> - + Now if you want to see this help message on your system type help(range) in the python interpreter. help(s) will return help message on the object s. Examples of range function ->> range(1,5) +>> range(1,5) [1, 2, 3, 4] >>> range(1,15,3) [1, 4, 7, 10, 13] >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ]]> - +
@@ -354,7 +366,7 @@ print "Goodbye"]]> The output - - +
@@ -371,7 +383,7 @@ Goodbye]]> We can have an optional else statement after any loop. It will be executed after the loop unless a break statement stopped the loop. ->> for i in range(0,5): +>> for i in range(0,5): ... print i ... else: ... print "Bye bye" @@ -382,7 +394,7 @@ Goodbye]]> 3 4 Bye bye]]> - + We will see more example of break and continue later in the book. diff --git a/en-US/modules.xml b/en-US/modules.xml index a4eeb26..e754860 100644 --- a/en-US/modules.xml +++ b/en-US/modules.xml @@ -18,43 +18,64 @@ Now we are going to see how modules work. Create a file called bars.py. Content of the file is given bellow. - - + - + Now we are going to start the python interpreter and import our module. - ->> import bars + +>> import bars >>> ]]> - + This will import the module bars. We have to use the module name to access functions inside the module. - ->> bars.hashbar(10) + +>> bars.hashbar(10) ########## >>> bars.simplebar(10) ---------- >>> bars.starbar(10) ********** ]]> - +
@@ -62,23 +83,12 @@ def simplebar(num): There are different ways to import modules. We already saw one way to do this. You can even import selected functions from modules. To do so: - ->> from bars import simplebar, starbar + +>> from bars import simplebar, starbar >>> simplebar(20) -------------------- ]]> - - - Or you can import all functions or variables from a module directly into the current namespace by using * - - ->> from bars import * ->>> hashbar(20) -#################### -]]> - +
Default modules @@ -86,9 +96,8 @@ def simplebar(num): Now your Python installation comes with different modules installed, you can use them as required and install new modules for any other special purposes. In the following few examples we are going to see many examples on the same. - ->> help() + +>> help() Welcome to Python 2.6! This is the online help utility. @@ -107,36 +116,52 @@ such as "spam", type "modules spam". help> modules ]]> - + The above example shows how to get the list of all installed modules in your system. I am not pasting them here as it is a big list in my system :)
+
+ Submodules + + We can many submodules inside a module. A directory with a __init__.py can also be used a module and all .py files inside it become submodules. + + + + + + In this example mymodule is the module name and bars and utils are two submodules in it. + +
Module os os module provides operating system dependent functionality. You can import it using the following import statement. - ->> import os + +>> import os ]]> - + getuid() function returns the current process's effective user's id. - + >> os.getuid() 500 ]]> - + getpid() returns the current process's id. getppid() returns the parent process's id. - + >> os.getpid() 16150 @@ -145,28 +170,28 @@ help> modules ]]> - + uname() returns different information identifying the operating system, in Linux it returns details you can get from the uname command. The returned object is a tuple, (sysname, nodename, release, version, machine) - + >> os.uname() ('Linux', 'd80', '2.6.34.7-56.fc13.i686.PAE', '#1 SMP Wed Sep 15 03:27:15 UTC 2010', 'i686') ]]> - + getcwd()returns the current working directory. chdir(path) changes the current working directory to path. In the example we first see the current directory which is my home directory and change the current directory to /tmp and then again checking the current directory. - + >> os.getcwd() '/home/kushal' >>> os.chdir('/tmp') >>> os.getcwd() '/tmp' ]]> - +
diff --git a/en-US/thebeginning.xml b/en-US/thebeginning.xml index 817e859..5bd7a16 100644 --- a/en-US/thebeginning.xml +++ b/en-US/thebeginning.xml @@ -13,13 +13,12 @@ Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> -
In our first code we are going to print "Hello World!" , so do it as below, ->>> print "Hello World!" +>>> print "Hello World!" Hello World! @@ -28,21 +27,23 @@ Hello World! Now as a serious programmer you may want to write the above code into a source file. We will create a helloworld.py. Use any text editor you like to create the file. I used vi, you can even use GUI based tools like Kate, gedit too. - -#!/usr/bin/env python + + +]]> + + To run the code first you have to make the file executable, in GNU/Linux you can do that by giving the command in a shell or terminal -$ chmod +x helloworld.py +$ chmod +x helloworld.py Then -$ ./helloworld.py +$ ./helloworld.py Hello World! diff --git a/en-US/virtualenv.xml b/en-US/virtualenv.xml new file mode 100644 index 0000000..ac24b5c --- /dev/null +++ b/en-US/virtualenv.xml @@ -0,0 +1,117 @@ + + + + + Virtualenv + + Virtual Python Environment builder or virtualenv is a tool which will help you to install different versions of python modules in a local directory using which you can develop and test your code without requiring to install everything systemwide. + +
+ Installation + + You can install virtualenv ewither from distro provided package or through pip. + +[user@host]$ sudo yum install python-virtualenv + + + Or + +$ sudo pip install virtualenv + +
+
+ Usage + + We will create a directory call virtual inside which we will have two different virtual environment. + + + The following commands will the create an env called virt1. + + +[user@host]$ cd virtual +[user@host]$ virtualenv virt1 +New python executable in virt1/bin/python +Installing setuptools............done. +Installing pip...............done. + + + Now we can go inside virt1 directory and then enable virt1 environment. + + +[user@host]$ source virt1/bin/activate +(virt1)[user@host]$ + + + The firt part of the prompt is now name of the virtual environment, it will help you to understand which environment you are in when you will have many environments. + + + To deactivate the environment use deactivate command. + + +(virt1)[user@host]$ deactivate +[user@host]$ + + + So, now we will install a python module called redis. + + +(virt1)[user@host]$ pip install redis +Downloading/unpacking redis + Downloading redis-2.6.2.tar.gz + Running setup.py egg_info for package redis + +Installing collected packages: redis + Running setup.py install for redis + +Successfully installed redis +Cleaning up... + + + Same way we can install a project called yolk, which can tell us which all modules are installed. + + +(virt1)[user@host]$ pip install yolk +(virt1)[user@host]$ yolk -l +Python - 2.7.3 - active development (/usr/lib64/python2.7/lib-dynload) +pip - 1.1 - active +redis - 2.6.2 - active +setuptools - 0.6c11 - active +wsgiref - 0.1.2 - active development (/usr/lib64/python2.7) +yolk - 0.4.3 - active + + + Now we will create another virtual environment virt2 where we will install same redis module but an old version 2.4 + + +[user@host]$ virtualenv virt2 +New python executable in virt1/bin/python +Installing setuptools............done. +Installing pip...............done. +[user@host]$ source virt2/bin/activate +(virt2[user@host]$ +(virt2)[user@host]$ pip install redis==2.4 +Downloading/unpacking redis + Downloading redis-2.4.0.tar.gz + Running setup.py egg_info for package redis + +Installing collected packages: redis + Running setup.py install for redis + +Successfully installed redis +Cleaning up... +(virt1)[user@host]$ pip install yolk +(virt1)[user@host]$ yolk -l +Python - 2.7.3 - active development (/usr/lib64/python2.7/lib-dynload) +pip - 1.1 - active +redis - 2.4.0 - active +setuptools - 0.6c11 - active +wsgiref - 0.1.2 - active development (/usr/lib64/python2.7) +yolk - 0.4.3 - active + + + As you can see yolk says that in this envrionment we have redis 2.4 installed. This way you can have many different environments for your all development needs. + +
+ +
\ No newline at end of file