You are on page 1of 53

This Download is from www.downloadmela.com .

The main motto of this website is to provide free download links of ebooks,video tutorials,magazines,previous papers,interview related content. To download more visit the website. If you like our services please help us in 2 ways. 1.Donate money. lease go through the link to donate http!""www.downloadmela.com"donate.html 2.Tell about this website to your friends,relatives.
Thanks for downloading. Enjoy the reading.

What is Python? ython is an interpreted, interactive, ob#ect$oriented programming language. It incorporates modules, e%ceptions, dynamic typing, very high level dynamic data types, and classes. ython combines remarkable power with very clear synta%. It has interfaces to many system calls and libraries, as well as to various window systems, and is e%tensible in & or &''. It is also usable as an e%tension language for applications that need a programmable interface. (inally, ython is portable! it runs on many )ni% variants, on the *ac, and on &s under *+$D,+, -indows, -indows .T, and ,+"2. Why can't I use an assignment in an expression? *any people used to & or erl complain that they want to use this & idiom! while /line 0 readline/f11 2 ...do something with line... 3 where in ython you4re forced to write this! while True! line 0 f.readline/1 if not line! break ...do something with line... The reason for not allowing assignment in ython e%pressions is a common, hard$to$find bug in those other languages, caused by this construct! if /% 0 51 2

6isit

http!""www.downloadmela.com"

for more papers

...error handling... 3 else 2 ...code that only works for nonzero %... 3 The error is a simple typo! % 0 5, which assigns 5 to the variable %, was written while the comparison % 00 5 is certainly what was intended. *any alternatives have been proposed. *ost are hacks that save some typing but use arbitrary or cryptic synta% or keywords, and fail the simple criterion for language change proposals! it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct. 7n interesting phenomenon is that most e%perienced ython programmers recognize the 8while True8 idiom and don4t seem to be missing the assignment in e%pression construct much9 it4s only newcomers who e%press a strong desire to add this to the language. There4s an alternative way of spelling this that seems attractive but is generally less robust than the 8while True8 solution! line 0 f.readline/1 while line! ...do something with line... line 0 f.readline/1 The problem with this is that if you change your mind about e%actly how you get the ne%t line /e.g. you want to change it into sys.stdin.readline/11 you have to remember to change two places in your program $$ the second occurrence is hidden at the bottom of the loop. The best approach is to use iterators, making it possible to loop through ob#ects using the for statement. (or e%ample, in the current version of ython file ob#ects support the iterator protocol, so you can now write simply! for line in f! ... do something with line... Is there a tool to help find bugs or perform static analysis? :es. y&hecker is a static analysis tool that finds bugs in ython source code and warns about code comple%ity and style. ylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug$ins to add a custom feature. How do you set a global variable in a function? Did you do something like this; % 0 1 < make a global def f/1! print % < try to print the global ... for # in range/1551! if =>?! %0@ 6isit

http!""www.downloadmela.com"

for more papers

7ny variable assigned in a function is local to that function. unless it is specifically declared global. +ince a value is bound to % as the last statement of the function body, the compiler assumes that % is local. &onse=uently the print % attempts to print an uninitialized local variable and will trigger a .ameArror. The solution is to insert an e%plicit global declaration at the start of the function! def f/1! global % print % < try to print the global ... for # in range/1551! if =>?! %0@ In this case, all references to % are interpreted as references to the % from the module namespace. What are the rules for local and global variables in Python? In ython, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function4s body, it4s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to e%plicitly declare it as 4global4. Though a bit surprising at first, a moment4s consideration e%plains this. ,n one hand, re=uiring global for assigned variables provides a bar against unintended side$effects. ,n the other hand, if global was re=uired for all global references, you4d be using global all the time. :ou4d have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side$effects. How do I share global variables across modules? The canonical way to share information across modules within a single program is to create a special module /often called config or cfg1. Bust import the config module in all modules of your application9 the module then becomes available as a global name. Cecause there is only one instance of each module, any changes made to the module ob#ect get reflected everywhere. (or e%ample! config.py! % 0 5 < Default value of the 4%4 configuration setting mod.py! import config config.% 0 1 main.py! import config import mod print config.% .ote that using a module is also the basis for implementing the +ingleton design pattern, for the same reason. How can I pass optional or keyword parameters from one function to another? 6isit

http!""www.downloadmela.com"

for more papers

&ollect the arguments using the D and DD specifier in the function4s parameter list9 this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. :ou can then pass these arguments when calling another function by using D and DD! def f/%, Dtup, DDkwargs1! ... kwargsE4width4F041@.?c4 ... g/%, Dtup, DDkwargs1 In the unlikely case that you care about ython versions older than 2.5, use 4apply4! def f/%, Dtup, DDkwargs1! ... kwargsE4width4F041@.?c4 ... apply/g, /%,1'tup, kwargs1 How do you make a higher order function in Python? :ou have two choices! you can use nested scopes or you can use callable ob#ects. (or e%ample, suppose you wanted to define linear/a,b1 which returns a function f/%1 that computes the value aD%'b. )sing nested scopes! def linear/a,b1! def result/%1! return aD% ' b return result ,r using a callable ob#ect! class linear! def GGinitGG/self, a, b1! self.a, self.b 0 a,b def GGcallGG/self, %1! return self.a D % ' self.b In both cases! ta%es 0 linear/5.?,21 gives a callable ob#ect where ta%es/15eH1 00 5.? D 15eH ' 2. The callable ob#ect approach has the disadvantage that it is a bit slower and results in slightly longer code. Iowever, note that a collection of callables can share their signature via inheritance! class e%ponential/linear1! < GGinitGG inherited 6isit

http!""www.downloadmela.com"

for more papers

def GGcallGG/self, %1! return self.a D /% DD self.b1 ,b#ect can encapsulate state for several methods! class counter! value 0 5 def set/self, %1! self.value 0 % def up/self1! self.value0self.value'1 def down/self1! self.value0self.value$1 count 0 counter/1 inc, dec, reset 0 count.up, count.down, count.set Iere inc/1, dec/1 and reset/1 act like functions which share the same counting variable. How do I copy an object in Python? In general, try copy.copy/1 or copy.deepcopy/1 for the general case. .ot all ob#ects can be copied, but most can. +ome ob#ects can be copied more easily. Dictionaries have a copy/1 method! newdict 0 olddict.copy/1 +e=uences can be copied by slicing! newGl 0 lE!F How can I find the methods or attributes of an object? (or an instance % of a user$defined class, dir/%1 returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class. How do I convert a string to a number? (or integers, use the built$in int/1 type constructor, e.g. int/41@@41 00 1@@. +imilarly, float/1 converts to floating$point, e.g. float/41@@41 00 1@@.5. Cy default, these interpret the number as decimal, so that int/451@@41 00 1@@ and int/45%1@@41 raises 6alueArror. int/string, base1 takes the base to convert from as a second optional argument, so int/45%1@@4, 1H1 00 ?2@. If the base is specified as 5, the number is interpreted using ython4s rules! a leading 454 indicates octal, and 45%4 indicates a he% number. Do not use the built$in function eval/1 if all you need is to convert strings to numbers. eval/1 will be significantly slower and it presents a security risk! someone could pass you a ython e%pression that might have unwanted side effects. (or e%ample, someone could pass GGimportGG/4os41.system/8rm $rf JI,*A81 which would erase your home directory. eval/1 also has the effect of interpreting numbers as ython e%pressions, so that e.g. eval/45K41 gives a

6isit

http!""www.downloadmela.com"

for more papers

synta% error because ython regards numbers starting with 454 as octal /base L1. How can my code discover the name of an object? Menerally speaking, it can4t, because ob#ects don4t really have names. Assentially, assignment always binds a name to a value9 The same is true of def and class statements, but in that case the value is a callable. &onsider the following code! class 7! pass C07 a 0 C/1 b0a print b NGGmainGG.7 instance at 51HD5O&&> print a NGGmainGG.7 instance at 51HD5O&&> 7rguably the class has a name! even though it is bound to two names and invoked through the name C the created instance is still reported as an instance of class 7. Iowever, it is impossible to say whether the instance4s name is a or b, since both names are bound to the same value. Menerally speaking it should not be necessary for your code to 8know the names8 of particular values. )nless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial. In comp.lang.python, (redrik Pundh once gave an e%cellent analogy in answer to this =uestion! The same way as you get the name of that cat you found on your porch! the cat /ob#ect1 itself cannot tell you its name, and it doesn4t really care $$ so the only way to find out what it4s called is to ask all your neighbours /namespaces1 if it4s their cat /ob#ect1... ....and don4t be surprised if you4ll find that it4s known by many names, or no name at allQ Is there an e uivalent of !'s "?#" ternary operator? .o. How do I convert a number to a string? To convert, e.g., the number 1@@ to the string 41@@4, use the built$in function str/1. If you want a he%adecimal or octal representation, use the built$in functions he%/1 or oct/1. (or fancy formatting, use the R operator on strings, e.g. 8R5@d8 R 1@@ yields 451@@4 and 8R.?f8 R /1"?.51 yields 45.???4. +ee the library reference manual for details. How do I modify a string in place? :ou can4t, because strings are immutable. If you need an ob#ect with this ability, try converting the string to a list or use the array module!

6isit

http!""www.downloadmela.com"

for more papers

>>> s 0 8Iello, world8 >>> a 0 list/s1 >>>print a E4I4, 4e4, 4l4, 4l4, 4o4, 4,4, 4 4, 4w4, 4o4, 4r4, 4l4, 4d4F >>> aEO!F 0 list/8thereQ81 >>>44.#oin/a1 4Iello, thereQ4 >>> import array >>> a 0 array.array/4c4, s1 >>> print a array/4c4, 4Iello, world41 >>> aE5F 0 4y4 9 print a array/4c4, 4yello world41 >>> a.tostring/1 4yello, world4 How do I use strings to call functions$methods? There are various techni=ues. D The best is to use a dictionary that maps strings to functions. The primary advantage of this techni=ue is that the strings do not need to match the names of the functions. This is also the primary techni=ue used to emulate a case construct! def a/1! pass def b/1! pass dispatch 0 24go4! a, 4stop4! b3 < .ote lack of parens for funcs dispatchEgetGinput/1F/1 < .ote trailing parens to call function D )se the built$in function getattr/1! import foo getattr/foo, 4bar41/1 .ote that getattr/1 works on any ob#ect, including classes, class instances, modules, and so on. This is used in several places in the standard library, like this! class (oo! def doGfoo/self1! 6isit

http!""www.downloadmela.com"

for more papers

... def doGbar/self1! ... f 0 getattr/fooGinstance, 4doG4 ' opname1 f/1 D )se locals/1 or eval/1 to resolve the function name! def my(unc/1! print 8hello8 fname 0 8my(unc8 f 0 locals/1EfnameF f/1 f 0 eval/fname1 f/1 .ote! )sing eval/1 is slow and dangerous. If you don4t have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being e%ecuted. Is there an e uivalent to Perl's chomp%& for removing trailing newlines from strings? +tarting with ython 2.2, you can use +.rstrip/8SrSn81 to remove all occurences of any line terminator from the end of the string + without removing other trailing whitespace. If the string + represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed! >>> lines 0 /8line 1 SrSn8 ... 8SrSn8 ... 8SrSn81 >>> lines.rstrip/8SnSr81 8line 1 8 +ince this is typically only desired when reading te%t one line at a time, using +.rstrip/1 this way works well. (or older versions of ython, There are two partial substitutes! D If you want to remove all trailing whitespace, use the rstrip/1 method of string ob#ects. This removes all trailing whitespace, not #ust a single newline. D ,therwise, if there is only one line in the string +, use +.splitlines/1E5F. Is there a scanf%& or sscanf%& e uivalent? .ot as such.

6isit

http!""www.downloadmela.com"

for more papers

(or simple input parsing, the easiest approach is usually to split the line into whitespace$delimited words using the split/1 method of string ob#ects and then convert decimal strings to numeric values using int/1 or float/1. split/1 supports an optional 8sep8 parameter which is useful if the line uses something other than whitespace as a separator. (or more complicated input parsing, regular e%pressions more powerful than &4s sscanf/1 and better suited for the task. Is there a scanf%& or sscanf%& e uivalent? .ot as such. (or simple input parsing, the easiest approach is usually to split the line into whitespace$delimited words using the split/1 method of string ob#ects and then convert decimal strings to numeric values using int/1 or float/1. split/1 supports an optional 8sep8 parameter which is useful if the line uses something other than whitespace as a separator. (or more complicated input parsing, regular e%pressions more powerful than &4s sscanf/1 and better suited for the task. 1.?.K -hat does 4)nicodeArror! 7+&II Edecoding,encodingF error! ordinal not in range/12L14 mean; This error indicates that your ython installation can handle only O$bit 7+&II strings. There are a couple ways to fi% or work around the problem. If your programs must handle data in arbitrary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. :ou need to convert the input to )nicode data using that encoding. (or e%ample, a program that handles email or web input will typically find character set encoding information in &ontent$Type headers. This can then be used to properly convert input data to )nicode. 7ssuming the string referred to by value is encoded as )T($L! value 0 unicode/value, 8utf$L81 will return a )nicode ob#ect. If the data is not correctly encoded as )T($L, the above call will raise a )nicodeArror e%ception. If you only want strings converted to )nicode which have non$7+&II data, you can try converting them first assuming an 7+&II encoding, and then generate )nicode ob#ects if that fails! try! % 0 unicode/value, 8ascii81 e%cept )nicodeArror! value 0 unicode/value, 8utf$L81 else! < value was valid 7+&II data pass

6isit

http!""www.downloadmela.com"

for more papers

It4s possible to set a default encoding in a file called sitecustomize.py that4s part of the ython library. Iowever, this isn4t recommended because changing the ython$wide default encoding may cause third$ party e%tension modules to fail. .ote that on -indows, there is an encoding known as 8mbcs8, which uses an encoding specific to your current locale. In many cases, and particularly when working with &,*, this may be an appropriate default encoding to use. How do I convert between tuples and lists? The function tuple/se=1 converts any se=uence /actually, any iterable1 into a tuple with the same items in the same order. (or e%ample, tuple/E1, 2, ?F1 yields /1, 2, ?1 and tuple/4abc41 yields /4a4, 4b4, 4c41. If the argument is a tuple, it does not make a copy but returns the same ob#ect, so it is cheap to call tuple/1 when you aren4t sure that an ob#ect is already a tuple. The function list/se=1 converts any se=uence or iterable into a list with the same items in the same order. (or e%ample, list//1, 2, ?11 yields E1, 2, ?F and list/4abc41 yields E4a4, 4b4, 4c4F. If the argument is a list, it makes a copy #ust like se=E!F would. What's a negative index? ython se=uences are inde%ed with positive numbers and negative numbers. (or positive numbers 5 is the first inde% 1 is the second inde% and so forth. (or negative indices $1 is the last inde% and $2 is the penultimate /ne%t to last1 inde% and so forth. Think of se=E$nF as the same as se=Elen/se=1$nF. )sing negative indices can be very convenient. (or e%ample +E!$1F is all of the string e%cept for its last character, which is useful for removing the trailing newline from a string. How do I iterate over a se uence in reverse order? If it is a list, the fastest solution is list.reverse/1 try! for % in list! 8do something with %8 finally! list.reverse/1 This has the disadvantage that while you are in the loop, the list is temporarily reversed. If you don4t like this, you can make a copy. This appears e%pensive but is actually faster than other solutions! rev 0 listE!F rev.reverse/1 for % in rev! Ndo something with %> If it4s not a list, a more general but slower solution is!

6isit

http!""www.downloadmela.com"

for more papers

for i in range/len/se=uence1$1, $1, $11! % 0 se=uenceEiF Ndo something with %> 7 more elegant solution, is to define a class which acts as a se=uence and yields the elements in reverse order /solution due to +teve *a#ewski1! class Tev! def GGinitGG/self, se=1! self.forw 0 se= def GGlenGG/self1! return len/self.forw1 def GGgetitemGG/self, i1! return self.forwE$/i ' 11F :ou can now simply write! for % in Tev/list1! Ndo something with %> )nfortunately, this solution is slowest of all, due to the method call overhead. -ith ython 2.?, you can use an e%tended slice synta%! for % in se=uenceE!!$1F! Ndo something with %> How do you remove duplicates from a list? If you don4t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go! if Pist! Pist.sort/1 last 0 PistE$1F for i in range/len/Pist1$2, $1, $11! if last00PistEiF! del PistEiF else! last0PistEiF If all elements of the list may be used as dictionary keys /i.e. they are all hash able1 this is often faster d 0 23 for % in Pist! dE%F0% Pist 0 d.values/1 How do you make an array in Python? )se a list! E8this8, 1, 8is8, 8an8, 8array8F

6isit

http!""www.downloadmela.com"

for more papers

Pists are e=uivalent to & or ascal arrays in their time comple%ity9 the primary difference is that a ython list can contain ob#ects of many different types. The array module also provides methods for creating arrays of fi%ed types with compact representations, but they are slower to inde% than lists. 7lso note that the .umeric e%tensions and others define array$like structures with various characteristics as well. To get Pisp$style linked lists, you can emulate cons cells using tuples! lispGlist 0 /8like8, /8this8, /8e%ample8, .one1 1 1 If mutability is desired, you could use lists instead of tuples. Iere the analogue of lisp car is lispGlistE5F and the analogue of cdr is lispGlistE1F. ,nly do this if you4re sure you really need to, because it4s usually a lot slower than using ython lists. How do I create a multidimensional list? :ou probably tried to make a multidimensional array like this! 7 0 EE.oneF D 2F D ? This looks correct if you print it! >>> 7 EE.one, .oneF, E.one, .oneF, E.one, .oneFF Cut when you assign a value, it shows up in multiple places! >>> 7E5FE5F 0 U >>> 7 EEU, .oneF, EU, .oneF, EU, .oneFF The reason is that replicating a list with D doesn4t create copies, it only creates references to the e%isting ob#ects. The D? creates a list containing ? references to the same list of length two. &hanges to one row will show in all rows, which is almost certainly not what you want. The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list! 7 0 E.oneFD? for i in range/?1! 7EiF 0 E.oneF D 2 This generates a list containing ? different lists of length two. :ou can also use a list comprehension! w,h 0 2,? 7 0 E E.oneFDw for i in range/h1 F 6isit

http!""www.downloadmela.com"

for more papers

,r, you can use an e%tension that provides a matri% datatype9 .umeric ython is the best known. How do I apply a method to a se uence of objects? )se a list comprehension! result 0 Eob#.method/1 for ob# in PistF *ore generically, you can try the following function! def methodGmap/ob#ects, method, arguments1! 888methodGmap/Ea,bF, 8meth8, /1,211 gives Ea.meth/1,21, b.meth/1,21F888 nob#ects 0 len/ob#ects1 methods 0 map/getattr, ob#ects, EmethodFDnob#ects1 return map/apply, methods, EargumentsFDnob#ects1 I want to do a complicated sort# can you do a 'chwart(man )ransform in Python? :es, it4s =uite simple with list comprehensions. The techni=ue, attributed to Tandal +chwartz of the erl community, sorts the elements of a list by a metric which maps each element to its 8sort value8. To sort a list of strings by their uppercase values! tmp1 0 E /%.upper/1, %1 for % in P F < +chwartzman transform tmp1.sort/1 )sorted 0 E %E1F for % in tmp1 F To sort by the integer value of a subfield e%tending from positions 15$1U in each string! tmp2 0 E /int/sE15!1UF1, s1 for s in P F < +chwartzman transform tmp2.sort/1 Isorted 0 E %E1F for % in tmp2 F .ote that Isorted may also be computed by def intfield/s1! return int/sE15!1UF1 def Icmp/s1, s21! return cmp/intfield/s11, intfield/s211 Isorted 0 PE!F Isorted.sort/Icmp1 but since this method calls intfield/1 many times for each element of P, it is slower than the +chwartzman Transform. How can I sort one list by values from another list? *erge them into a single list of tuples, sort the resulting list, and then pick out the element you want. 6isit

http!""www.downloadmela.com"

for more papers

>>> list1 0 E8what8, 8I4m8, 8sorting8, 8by8F >>> list2 0 E8something8, 8else8, 8to8, 8sort8F >>> pairs 0 zip/list1, list21 >>> pairs E/4what4, 4something41, /8I4m8, 4else41, /4sorting4, 4to41, /4by4, 4sort41F >>> pairs.sort/1 >>> result 0 E %E1F for % in pairs F >>> result E4else4, 4sort4, 4to4, 4something4F 7n alternative for the last step is! result 0 EF for p in pairs! result.append/pE1F1 If you find this more legible, you might prefer to use this instead of the final list comprehension. Iowever, it is almost twice as slow for long lists. -hy; (irst, the append/1 operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs =uite a bit. +econd, the e%pression 8result.append8 re=uires an e%tra attribute lookup, and third, there4s a speed reduction from having to make all those function calls. What is a class? 7 class is the particular ob#ect type created by e%ecuting a class statement. &lass ob#ects are used as templates to create instance ob#ects, which embody both the data /attributes1 and code /methods1 specific to a datatype. 7 class can be based on one or more other classes, called its base class/es1. It then inherits the attributes and methods of its base classes. This allows an ob#ect model to be successively refined by inheritance. :ou might have a generic *ailbo% class that provides basic accessor methods for a mailbo%, and subclasses such as *bo%*ailbo%, *aildir*ailbo%, ,utlook*ailbo% that handle various specific mailbo% formats. What is a method? 7 method is a function on some ob#ect % that you normally call as %.name/arguments...1. *ethods are defined as functions inside the class definition! class &! def meth /self, arg1! return argD2 ' self.attribute What is self? +elf is merely a conventional name for the first argument of a method. 7 method defined as meth/self, a, b, c1 should be called as %.meth/a, b, c1 for some instance % of the class in which the definition occurs9 the called method will think it is called as meth/%, a, b, c1. How do I check if an object is an instance of a given class or of a subclass of it? )se the built$in function isinstance/ob#, cls1. :ou can check if an ob#ect is an instance of any of a

6isit

http!""www.downloadmela.com"

for more papers

number of classes by providing a tuple instead of a single class, e.g. isinstance/ob#, /class1, class2, ...11, and can also check whether an ob#ect is one of ython4s built$in types, e.g. isinstance/ob#, str1 or isinstance/ob#, /int, long, float, comple%11. .ote that most programs do not use isinstance/1 on user$defined classes very often. If you are developing the classes yourself, a more proper ob#ect$oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the ob#ect4s class and doing a different thing based on what class it is. (or e%ample, if you have a function that does something! def search /ob#1! if isinstance/ob#, *ailbo%1! < ... code to search a mailbo% elif isinstance/ob#, Document1! < ... code to search a document elif ... 7 better approach is to define a search/1 method on all the classes and #ust call it! class *ailbo%! def search/self1! < ... code to search a mailbo% class Document! def search/self1! < ... code to search a document ob#.search/1 What is delegation? Delegation is an ob#ect oriented techni=ue /also called a design pattern1. Pet4s say you have an ob#ect % and want to change the behavior of #ust one of its methods. :ou can create a new class that provides a new implementation of the method you4re interested in changing and delegates all other methods to the corresponding method of %. ython programmers can easily implement delegation. (or e%ample, the following class implements a class that behaves like a file but converts all written data to uppercase! class )pper,ut! def GGinitGG/self, outfile1! self.GGoutfile 0 outfile def write/self, s1! self.GGoutfile.write/s.upper/11 def GGgetattrGG/self, name1! return getattr/self.GGoutfile, name1 Iere the )pper,ut class redefines the write/1 method to convert the argument string to uppercase before calling the underlying self.GGoutfile.write/1 method. 7ll other methods are delegated to the 6isit

http!""www.downloadmela.com"

for more papers

underlying self.GGoutfile ob#ect. The delegation is accomplished via the GGgetattrGG method9 consult the language reference for more information about controlling attribute access. .ote that for more general cases delegation can get trickier. -hen attributes must be set as well as retrieved, the class must define a GGsettattrGG method too, and it must do so carefully. The basic implementation of GGsetattrGG is roughly e=uivalent to the following! class V! ... def GGsetattrGG/self, name, value1! self.GGdictGGEnameF 0 value ... *ost GGsetattrGG implementations must modify self.GGdictGG to store local state for self without causing an infinite recursion. How do I call a method defined in a base class from a derived class that overrides it? If you4re using new$style classes, use the built$in super/1 function! class Derived/Case1! def meth /self1! super/Derived, self1.meth/1 If you4re using classic classes! (or a class definition such as class Derived/Case1! ... you can call method meth/1 defined in Case /or one of Case4s base classes1 as Case.meth/self, arguments...1. Iere, Case.meth is an unbound method, so you need to provide the self argument. How can I organi(e my code to make it easier to change the base class? :ou could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically /e.g. depending on availability of resources1 which base class to use. A%ample! Case7lias 0 Nreal base class> class Derived/Case7lias1! def meth/self1! Case7lias.meth/self1 How do I create static class data and static class methods? +tatic data /in the sense of &'' or Bava1 is easy9 static methods /again in the sense of &'' or Bava1 are not supported directly. (or static data, simply define a class attribute. To assign a new value to the attribute, you have to e%plicitly use the class name in the assignment! class &! count 0 5 < number of times &.GGinitGG called

6isit

http!""www.downloadmela.com"

for more papers

def GGinitGG/self1! &.count 0 &.count ' 1 def getcount/self1! return &.count < or return self.count c.count also refers to &.count for any c such that isinstance/c, &1 holds, unless overridden by c itself or by some class on the base$class search path from c.GGclassGG back to &. &aution! within a method of &, an assignment like self.count 0 @2 creates a new and unrelated instance vrbl named 8count8 in self4s own dict. Tebinding of a class$static data name must always specify the class whether inside a method or not! &.count 0 ?1@ +tatic methods are possible when you4re using new$style classes! class &! def static/arg1, arg2, arg?1! < .o 4self4 parameterQ ... static 0 staticmethod/static1 Iowever, a far more straightforward way to get the effect of a static method is via a simple module$ level function! def getcount/1! return &.count If your code is structured so as to define one class /or tightly related class hierarchy1 per module, this supplies the desired encapsulation. How can I overload constructors %or methods& in Python? This answer actually applies to all methods, but the =uestion usually comes up first in the conte%t of constructors. In &'' you4d write class & 2 &/1 2 cout NN 8.o argumentsSn89 3 &/int i1 2 cout NN 87rgument is 8 NN i NN 8Sn89 3 3 in ython you have to write a single constructor that catches all cases using default arguments. (or e%ample! class &! 6isit

http!""www.downloadmela.com"

for more papers

def GGinitGG/self, i0.one1! if i is .one! print 8.o arguments8 else! print 87rgument is8, i This is not entirely e=uivalent, but close enough in practice. :ou could also try a variable$length argument list, e.g. def GGinitGG/self, Dargs1! .... The same approach works for all method definitions. How do I find the current module name? 7 module can find out its own module name by looking at the predefined global variable GGnameGG. If this has the value 4GGmainGG4, the program is running as a script. *any modules that are usually used by importing them also provide a command$line interface or a self$test, and only e%ecute this code after checking GGnameGG! def main/1! print 4Tunning test...4 ... if GGnameGG 00 4GGmainGG4! main/1 GGimportGG/4%.y.z41 returns Try! GGimportGG/4%.y.z41.y.z (or more realistic situations, you may have to do something like m 0 GGimportGG/s1 for i in s.split/8.81E1!F! m 0 getattr/m, i1 When I edit an imported module and reimport it* the changes don't show up+ Why does this happen? (or reasons of efficiency as well as consistency, ython only reads the module file on the first time a module is imported. If it didn4t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re$parsed many times. To force rereading of a changed module, do this! import modname reload/modname1

6isit

http!""www.downloadmela.com"

for more papers

-arning! this techni=ue is not 155R fool$proof. In particular, modules containing statements like from modname import someGob#ects will continue to work with the old version of the imported ob#ects. If the module contains class definitions, e%isting class instances will not be updated to use the new class definition. This can result in the following parado%ical behavior! >>> import cls >>> c 0 cls.&/1 < &reate an instance of & >>> reload/cls1 Nmodule 4cls4 from 4cls.pyc4> >>> isinstance/c, cls.&1 < isinstance is false;Q; (alse The nature of the problem is made clear if you print out the class ob#ects! >>> c.GGclassGG Nclass cls.& at 5%O?U2a5> >>> cls.& Nclass cls.& at 5%@1KLd5> Where is the math+py %socket+py* regex+py* etc+& source file? There are /at least1 three kinds of modules in ython! 1. modules written in ython /.py19 2. modules written in & and dynamically loaded /.dll, .pyd, .so, .sl, etc19 ?. modules written in & and linked with the interpreter9 to get a list of these, type! import sys print sys.builtinGmoduleGnames How do I make a Python script executable on ,nix? :ou need to do two things! the script file4s mode must be e%ecutable and the first line must begin with <Q followed by the path of the ython interpreter. The first is done by e%ecuting chmod '% scriptfile or perhaps chmod OUU scriptfile. The second can be done in a number of ways. The most straightforward way is to write <Q"usr"local"bin"python as the very first line of your file, using the pathname for where the ython interpreter is installed on your platform. If you would like the script to be independent of where the ython interpreter lives, you can use the 8env8 program. 7lmost all )ni% variants support the following, assuming the python interpreter is in a directory on the user4s J 7TI!

6isit

http!""www.downloadmela.com"

for more papers

<Q "usr"bin"env python Don4t do this for &MI scripts. The J 7TI variable for &MI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter. ,ccasionally, a user4s environment is so full that the "usr"bin"env program fails9 or there4s no env program at all. In that case, you can try the following hack /due to 7le% Tezinsky1! <Q "bin"sh 888!8 e%ec python J5 J21'8JW83 888 The minor disadvantage is that this defines the script4s GGdocGG string. Iowever, you can fi% that by adding GGdocGG 0 888...-hatever...888 Why don't my signal handlers work? The most common problem is that the signal handler is declared with the wrong argument list. It is called as handler/signum, frame1 so it should be declared with two arguments! def handler/signum, frame1! ... How do I test a Python program or component? ython comes with two testing frameworks. The doctest module finds e%amples in the docstrings for a module and runs them, comparing the output with the e%pected output given in the docstring. The unittest module is a fancier testing framework modelled on Bava and +malltalk testing frameworks. (or testing, it helps to write the program so that it may be easily tested by using good modular design. :our program should have almost all functionality encapsulated in either functions or class methods $$ and this sometimes has the surprising and delightful effect of making the program run faster /because local variable accesses are faster than global accesses1. (urthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do. The 8global main logic8 of your program may be as simple as if GGnameGG008GGmainGG8! mainGlogic/1

6isit

http!""www.downloadmela.com"

for more papers

at the bottom of the main module of your program. ,nce your program is organized as a tractable collection of functions and class behaviours you should write test functions that e%ercise the behaviours. 7 test suite can be associated with each module which automates a se=uence of tests. This sounds like a lot of work, but since ython is so terse and fle%ible it4s surprisingly easy. :ou can make coding much more pleasant and fun by writing your test functions in parallel with the 8production code8, since this makes it easy to find bugs and even design flaws earlier. 8+upport modules8 that are not intended to be the main module of a program may include a self$test of the module. if GGnameGG 00 8GGmainGG8! selfGtest/1 Aven programs that interact with comple% e%ternal interfaces may be tested when the e%ternal interfaces are unavailable by using 8fake8 interfaces implemented in ython. -one of my threads seem to run# why? 7s soon as the main thread e%its, all threads are killed. :our main thread is running too =uickly, giving the threads no time to do any work. 7 simple fi% is to add a sleep to the end of the program that4s long enough for all the threads to finish! import threading, time def threadGtask/name, n1! for i in range/n1! print name, i for i in range/151! T 0 threading.Thread/target0threadGtask, args0/str/i1, i11 T.start/1 time.sleep/151 < N$$$$$$$$$$$$$$$$$$$$$$$$$$$$Q Cut now /on many platforms1 the threads don4t run in parallel, but appear to run se=uentially, one at a timeQ The reason is that the ,+ thread scheduler doesn4t start a new thread until the previous thread is blocked. 7 simple fi% is to add a tiny sleep to the start of the run function! def threadGtask/name, n1! time.sleep/5.5511 < N$$$$$$$$$$$$$$$$$$$$$Q for i in range/n1! print name, i

6isit

http!""www.downloadmela.com"

for more papers

for i in range/151! T 0 threading.Thread/target0threadGtask, args0/str/i1, i11 T.start/1 time.sleep/151 Instead of trying to guess how long a time.sleep/1 delay will be enough, it4s better to use some kind of semaphore mechanism. ,ne idea is to use the Xueue module to create a =ueue ob#ect, let each thread append a token to the =ueue when it finishes, and let the main thread read as many tokens from the =ueue as there are threads. How do I parcel out work among a bunch of worker threads? )se the Xueue module to create a =ueue containing a list of #obs. The Xueue class maintains a list of ob#ects with .put/ob#1 to add an item to the =ueue and .get/1 to return an item. The class will take care of the locking necessary to ensure that each #ob is handed out e%actly once. Iere4s a trivial e%ample! import threading, Xueue, time < The worker thread gets #obs off the =ueue. -hen the =ueue is empty, it < assumes there will be no more work and e%its. < /Tealistically workers will run until terminated.1 def worker /1! print 4Tunning worker4 time.sleep/5.11 while True! try! arg 0 =.get/block0(alse1 e%cept Xueue.Ampty! print 4-orker4, threading.currentThread/1, print 4=ueue empty4 break else! print 4-orker4, threading.currentThread/1, print 4running with argument4, arg time.sleep/5.U1 < &reate =ueue = 0 Xueue.Xueue/1 < +tart a pool of U workers for i in range/U1! t 0 threading.Thread/target0worker, name04worker Ri4 R /i'111 t.start/1 < Cegin adding work to the =ueue 6isit

http!""www.downloadmela.com"

for more papers

for i in range/U51! =.put/i1 < Mive threads time to run print 4*ain thread sleeping4 time.sleep/U1 -hen run, this will produce the following output! Tunning worker Tunning worker Tunning worker Tunning worker Tunning worker *ain thread sleeping -orker NThread/worker 1, started1> running with argument 5 -orker NThread/worker 2, started1> running with argument 1 -orker NThread/worker ?, started1> running with argument 2 -orker NThread/worker @, started1> running with argument ? -orker NThread/worker U, started1> running with argument @ -orker NThread/worker 1, started1> running with argument U ... How do I delete a file? %.nd other file uestions+++& )se os.remove/filename1 or os.unlink/filename19 How do I copy a file? The shutil module contains a copyfile/1 function. How do I read %or write& binary data? or comple% data formats, it4s best to use the struct module. It allows you to take a string containing binary data /usually numbers1 and convert it to ython ob#ects9 and vice versa. (or e%ample, the following code reads two 2$byte integers and one @$byte integer in big$endian format from a file! import struct f 0 open/filename, 8rb81 < ,pen in binary mode for portability s 0 f.read/L1 %, y, z 0 struct.unpack/8>hhl8, s1 The 4>4 in the format string forces big$endian data9 the letter 4h4 reads one 8short integer8 /2 bytes1, and 4l4 reads one 8long integer8 /@ bytes1 from the string. How do I run a subprocess with pipes connected to both input and output? )se the popen2 module. (or e%ample! import popen2 fromchild, tochild 0 popen2.popen2/8command81 tochild.write/8inputSn81 tochild.flush/1 output 0 fromchild.readline/1 How can I mimic !/I form submission %01)H234P2')&? I would like to retrieve web pages that are the result of ,+Ting a form. Is there e%isting code that 6isit

http!""www.downloadmela.com"

for more papers

would let me do this easily; :es. Iere4s a simple e%ample that uses httplib! <Q"usr"local"bin"python import httplib, sys, time <<< build the =uery string =s 0 8(irst0BosephineY*I0XYPast0 ublic8 <<< connect and send the server a path httpob# 0 httplib.ITT /4www.some$server.out$there4, L51 httpob#.putre=uest/4 ,+T4, 4"cgi$bin"some$cgi$script41 <<< now generate the rest of the ITT headers... httpob#.putheader/47ccept4, 4D"D41 httpob#.putheader/4&onnection4, 4Zeep$7live41 httpob#.putheader/4&ontent$type4, 4application"%$www$form$urlencoded41 httpob#.putheader/4&ontent$length4, 4Rd4 R len/=s11 httpob#.endheaders/1 httpob#.send/=s1 <<< find out what the server said in response... reply, msg, hdrs 0 httpob#.getreply/1 if reply Q0 255! sys.stdout.write/httpob#.getfile/1.read/11 .ote that in general for )TP$encoded ,+T operations, =uery strings must be =uoted by using urllib.=uote/1. (or e%ample to send name08Muy +teele, Br.8! >>> from urllib import =uote >>> % 0 =uote/8Muy +teele, Br.81 >>> % 4MuyR25+teele,R25Br.4 >>> =ueryGstring 0 8name08'% >>> =ueryGstring 4name0MuyR25+teele,R25Br.4 How do I send mail from a Python script? )se the standard library module smtplib. Iere4s a very simple interactive mail sender that uses it. This method will work on any host that supports an +*T listener. import sys, smtplib fromaddr 0 rawGinput/8(rom! 81 toaddrs 0 rawGinput/8To! 81.split/4,41 6isit

http!""www.downloadmela.com"

for more papers

print 8Anter message, end with [D!8 msg 0 44 while 1! line 0 sys.stdin.readline/1 if not line! break msg 0 msg ' line < The actual mail send server 0 smtplib.+*T /4localhost41 server.sendmail/fromaddr, toaddrs, msg1 server.=uit/1 7 )ni%$only alternative uses sendmail. The location of the sendmail program varies between systems9 sometimes it is "usr"lib"sendmail, sometime "usr"sbin"sendmail. The sendmail manual page will help you out. Iere4s some sample code! +A.D*7IP 0 8"usr"sbin"sendmail8 < sendmail location import os p 0 os.popen/8Rs $t $i8 R +A.D*7IP, 8w81 p.write/8To! receiverWe%ample.comSn81 p.write/8+ub#ect! testSn81 p.write/8Sn81 < blank line separating headers from body p.write/8+ome te%tSn81 p.write/8some more te%tSn81 sts 0 p.close/1 if sts Q0 5! print 8+endmail e%it status8, sts How do I avoid blocking in the connect%& method of a socket? The select module is commonly used to help with asynchronous I", on sockets. .re there any interfaces to database packages in Python? :es. ython 2.? includes the bsddb package which provides an interface to the CerkeleyDC library. Interfaces to disk$based hashes such as DC* and MDC* are also included with standard ython. How do I generate random numbers in Python? The standard module random implements a random number generator. )sage is simple! import random random.random/1 This returns a random floating point number in the range E5, 11. !an I create my own functions in !? :es, you can create built$in modules containing functions, variables, e%ceptions and even new types in

6isit

http!""www.downloadmela.com"

for more papers

&. !an I create my own functions in !55? :es, using the & compatibility features found in &''. lace e%tern 8&8 2 ... 3 around the ython include files and put e%tern 8&8 before each function that is going to be called by the ython interpreter. Mlobal or static &'' ob#ects with constructors are probably not a good idea. How can I execute arbitrary Python statements from !? The highest$level function to do this is yTunG+imple+tring/1 which takes a single string argument to be e%ecuted in the conte%t of the module GGmainGG and returns 5 for success and $1 when an e%ception occurred /including +ynta%Arror1. If you want more control, use yTunG+tring/19 see the source for yTunG+imple+tring/1 in ython"pythonrun.c. How can I evaluate an arbitrary Python expression from !? &all the function yTunG+tring/1 from the previous =uestion with the start symbol yGevalGinput9 it parses an e%pression, evaluates it and returns its value. How do I extract ! values from a Python object? That depends on the ob#ect4s type. If it4s a tuple, yTuple+ize/o1 returns its length and yTupleGMetItem/o, i1 returns its i4th item. Pists have similar functions, yPist+ize/o1 and yPistGMetItem/o, i1. (or strings, y+tringG+ize/o1 returns its length and y+tringG7s+tring/o1 a pointer to its value. .ote that ython strings may contain null bytes so &4s strlen/1 should not be used. To test the type of an ob#ect, first make sure it isn4t .)PP, and then use y+tringG&heck/o1, yTupleG&heck/o1, yPistG&heck/o1, etc. There is also a high$level 7 I to ython ob#ects which is provided by the so$called 4abstract4 interface $$ read Include"abstract.h for further details. It allows interfacing with any kind of ython se=uence using calls like y+e=uenceGPength/1, y+e=uenceGMetItem/1, etc.1 as well as many other useful protocols. How do I call an object's method from !? The y,b#ectG&all*ethod/1 function can be used to call an arbitrary method of an ob#ect. The parameters are the ob#ect, the name of the method to call, a format string like that used with yGCuild6alue/1, and the argument values! y,b#ect D y,b#ectG&all*ethod/ y,b#ect Dob#ect, char DmethodGname, char DargGformat, ...19 This works for any ob#ect that has methods $$ whether built$in or user$defined. :ou are responsible for eventually yGDA&TA(4ing the return value. To call, e.g., a file ob#ect4s 8seek8 method with arguments 15, 5 /assuming the file ob#ect pointer is 8f81! res 0 y,b#ectG&all*ethod/f, 8seek8, 8/ii18, 15, 519 if /res 00 .)PP1 2 6isit

http!""www.downloadmela.com"

for more papers

... an e%ception occurred ... 3 else 2 yGDA&TA(/res19 3 .ote that since y,b#ectG&all,b#ect/1 always wants a tuple for the argument list, to call a function without arguments, pass 8/18 for the format, and to call a function with one argument, surround the argument in parentheses, e.g. 8/i18. How do I catch the output from Py1rr6Print%& %or anything that prints to stdout$stderr&? In ython code, define an ob#ect that supports the write/1 method. 7ssign this ob#ect to sys.stdout and sys.stderr. &all printGerror, or #ust allow the standard traceback mechanism to work. Then, the output will go wherever your write/1 method sends it. The easiest way to do this is to use the +tringI, class in the standard library. +ample code and use for catching stdout! >>> class +tdout&atcher! ... def GGinitGG/self1! ... self.data 0 44 ... def write/self, stuff1! ... self.data 0 self.data ' stuff ... >>> import sys >>> sys.stdout 0 +tdout&atcher/1 >>> print 4foo4 >>> print 4hello worldQ4 >>> sys.stderr.write/sys.stdout.data1 foo hello worldQ How do I access a module written in Python from !? :ou can get a pointer to the module ob#ect as follows! module 0 yImportGImport*odule/8Nmodulename>819 If the module hasn4t been imported yet /i.e. it is not yet present in sys.modules1, this initializes the module9 otherwise it simply returns the value of sys.modulesE8Nmodulename>8F. .ote that it doesn4t enter the module into any namespace $$ it only ensures it has been initialized and is stored in sys.modules. :ou can then access the module4s attributes /i.e. any name defined in the module1 as follows! attr 0 y,b#ectGMet7ttr+tring/module, 8Nattrname>819

6isit

http!""www.downloadmela.com"

for more papers

&alling y,b#ectG+et7ttr+tring/1 to assign to variables in the module also works. How do I interface to !55 objects from Python? Depending on your re=uirements, there are many approaches. To do this manually, begin by reading the 8A%tending and Ambedding8 document. Tealize that for the ython run$time system, there isn4t a whole lot of difference between & and &'' $$ so the strategy of building a new ython type around a & structure /pointer1 type will also work for &'' ob#ects. How do I tell "incomplete input" from "invalid input"? +ometimes you want to emulate the ython interactive interpreter4s behavior, where it gives you a continuation prompt when the input is incomplete /e.g. you typed the start of an 8if8 statement or you didn4t close your parentheses or triple string =uotes1, but it gives you a synta% error message immediately when the input is invalid. In ython you can use the codeop module, which appro%imates the parser4s behavior sufficiently. IDPA uses this, for e%ample. The easiest way to do it in & is to call yTunGInteractivePoop/1 /perhaps in a separate thread1 and let the ython interpreter handle the input for you. :ou can also set the y,+GTeadline(unction ointer to point at your custom input function. +ee *odules"readline.c and arser"myreadline.c for more hints. Iowever sometimes you have to run the embedded ython interpreter in the same thread as your rest application and you can4t allow the yTunGInteractivePoop/1 to stop while waiting for user input. The one solution then is to call y arserG arse+tring/1 and test for e.error e=ual to AGA,(, which means the input is incomplete1. Iere4s a sample code fragment, untested, inspired by code from 7le% (arber! <include N ython.h> <include Nnode.h> <include Nerrcode.h> <include Ngrammar.h> <include Nparsetok.h> <include Ncompile.h> int testcomplete/char Dcode1 "D code should end in Sn D" "D return $1 for error, 5 for incomplete, 1 for complete D" 2 node Dn9 perrdetail e9 n 0 y arserG arse+tring/code, YG y arserGMrammar, yGfileGinput, Ye19 if /n 00 .)PP1 2 if /e.error 00 AGA,(1 return 59 return $19 3

6isit

http!""www.downloadmela.com"

for more papers

y.odeG(ree/n19 return 19 3 7nother solution is trying to compile the received string with yG&ompile+tring/1. If it compiles without errors, try to e%ecute the returned code ob#ect by calling yAvalGAval&ode/1. ,therwise save the input for later. If the compilation fails, find out if it4s an error or #ust more input is re=uired $ by e%tracting the message string from the e%ception tuple and comparing it to the string 8une%pected A,( while parsing8. Iere is a complete e%ample using the M.) readline library /you may want to ignore +IMI.T while calling readline/11! <include Nstdio.h> <include Nreadline.h> <include N ython.h> <include Nob#ect.h> <include Ncompile.h> <include Neval.h> int main /int argc, charD argvEF1 2 int i, #, done 0 59 "D lengths of line, code D" char ps1EF 0 8>>> 89 char ps2EF 0 8... 89 char Dprompt 0 ps19 char Dmsg, Dline, Dcode 0 .)PP9 y,b#ect Dsrc, Dglb, Dloc9 y,b#ect De%c, Dval, Dtrb, Dob#, Ddum9 yGInitialize /19 loc 0 yDictG.ew /19 glb 0 yDictG.ew /19 yDictG+etItem+tring /glb, 8GGbuiltinsGG8, yAvalGMetCuiltins /119 while /Qdone1 2 line 0 readline /prompt19 if /.)PP 00 line1 "D &TTP$D pressed D" 2 done 0 19 3 else 2 6isit

http!""www.downloadmela.com"

for more papers

i 0 strlen /line19 if /i > 51 addGhistory /line19 "D save non$empty lines D" if /.)PP 00 code1 "D nothing in code yet D" # 0 59 else # 0 strlen /code19 code 0 realloc /code, i ' # ' 219 if /.)PP 00 code1 "D out of memory D" e%it /119 if /5 00 #1 "D code was empty, so D" codeE5F 0 4S549 "D keep strncat happy D" strncat /code, line, i19 "D append line to code D" codeEi ' #F 0 4Sn49 "D append 4Sn4 to code D" codeEi ' # ' 1F 0 4S549 src 0 yG&ompile+tring /code, 8 Nstdin>8, yGsingleGinput19 if /.)PP Q0 src1 "D compiled #ust fine $ D" 2 if /ps1 00 prompt \\ "D 8>>> 8 or D" 4Sn4 00 codeEi ' # $ 1F1 "D 8... 8 and double 4Sn4 D" 2 "D so e%ecute it D" dum 0 yAvalGAval&ode // y&ode,b#ect D1src, glb, loc19 yGVDA&TA( /dum19 yGVDA&TA( /src19 free /code19 code 0 .)PP9 if / yArrG,ccurred /11 yArrG rint /19 6isit

http!""www.downloadmela.com"

for more papers

prompt 0 ps19 3 3 "D synta% error or AGA,(; D" else if / yArrGA%ception*atches / yA%cG+ynta%Arror11 2 yArrG(etch /Ye%c, Yval, Ytrb19 "D clears e%ceptionQ D" if / y7rgG arseTuple /val, 8s,8, Ymsg, Yob#1 YY Qstrcmp /msg, 8une%pected A,( while parsing811 "D AGA,( D" 2 yGVDA&TA( /e%c19 yGVDA&TA( /val19 yGVDA&TA( /trb19 prompt 0 ps29 3 else "D some other synta% error D" 2 yArrGTestore /e%c, val, trb19 yArrG rint /19 free /code19 code 0 .)PP9 prompt 0 ps19 3 3 else "D some non$synta% error D" 2 yArrG rint /19 free /code19 code 0 .)PP9 prompt 0 ps19 3 free /line19 3 3 yGVDA&TA(/glb19 yGVDA&TA(/loc19 yG(inalize/19 e%it/519 3 6isit

http!""www.downloadmela.com"

for more papers

How do I run a Python program under Windows? This is not necessarily a straightforward =uestion. If you are already familiar with running programs from the -indows command line then everything will seem obvious9 otherwise, you might need a little more guidance. There are also differences between -indows KU, KL, .T, *A, 2555 and V which can add to the confusion. )nless you use some sort of integrated development environment, you will end up typing -indows commands into what is variously referred to as a 8D,+ window8 or 8&ommand prompt window8. )sually you can create such a window from your +tart menu9 under -indows 2555 the menu selection is 8+tart \ rograms \ 7ccessories \ &ommand rompt8. :ou should be able to recognize when you have started such a window because you will see a -indows 8command prompt8, which usually looks like this! &!S> The letter may be different, and there might be other things after it, so you might #ust as easily see something like! D!S+teveS ro#ectsS ython> depending on how your computer has been set up and what else you have recently done with it. ,nce you have started such a window, you are well on the way to running ython programs. :ou need to realize that your ython scripts have to be processed by another program called the ython interpreter. The interpreter reads your script, compiles it into bytecodes, and then e%ecutes the bytecodes to run your program. +o, how do you arrange for the interpreter to handle your ython; (irst, you need to make sure that your command window recognises the word 8python8 as an instruction to start the interpreter. If you have opened a command window, you should try entering the command python and hitting return. :ou should then see something like! ython 2.2 /<2L, Dec 21 2551, 12!21!221 E*+& ?2 bit /Intel1F on win?2 Type 8help8, 8copyright8, 8credits8 or 8license8 for more information. >>> :ou have started the interpreter in 8interactive mode8. That means you can enter ython statements or e%pressions interactively and have them e%ecuted or evaluated while you wait. This is one of ython4s strongest features. &heck it by entering a few e%pressions of your choice and seeing the results! >>> print 8Iello8 Iello >>> 8Iello8 D ? IelloIelloIello *any people use the interactive mode as a convenient yet highly programmable calculator. -hen you 6isit

http!""www.downloadmela.com"

for more papers

want to end your interactive ython session, hold the &trl key down while you enter a ], then hit the 8Anter8 key to get back to your -indows command prompt. :ou may also find that you have a +tart$menu entry such as 8+tart \ rograms \ ython 2.2 \ ython /command line18 that results in you seeing the >>> prompt in a new window. If so, the window will disappear after you enter the &trl$] character9 -indows is running a single 8python8 command in the window, and closes it when you terminate the interpreter. If the python command, instead of displaying the interpreter prompt >>>, gives you a message like! 4python4 is not recognized as an internal or e%ternal command, operable program or batch file. or! Cad command or filename then you need to make sure that your computer knows where to find the ython interpreter. To do this you will have to modify a setting called 7TI, which is a list of directories where -indows will look for programs. :ou should arrange for ython4s installation directory to be added to the 7TI of every command window as it starts. If you installed ython fairly recently then the command dir &!SpyD will probably tell you where it is installed9 the usual location is something like &!S ython2?. ,therwise you will be reduced to a search of your whole disk ... use 8Tools \ (ind8 or hit the 8+earch8 button and look for 8python.e%e8. +upposing you discover that ython is installed in the &!S ython2? directory /the default at the time of writing1, you should make sure that entering the command c!S ython2?Spython starts up the interpreter as above /and don4t forget you4ll need a 8&TTP$]8 and an 8Anter8 to get out of it1. ,nce you have verified the directory, you need to add it to the start$up routines your computer goes through. (or older versions of -indows the easiest way to do this is to edit the &!S7)T,AVA&.C7T file. :ou would want to add a line like the following to 7)T,AVA&.C7T! 7TI &!S ython2?9R 7TIR (or -indows .T, 2555 and /I assume1 V , you will need to add a string such as 9&!S ython2? to the current setting for the 7TI environment variable, which you will find in the properties window of 8*y &omputer8 under the 87dvanced8 tab. .ote that if you have sufficient privilege you might get a choice of installing the settings either for the &urrent )ser or for +ystem. The latter is preferred if you want everybody to be able to run ython on the machine. 6isit

http!""www.downloadmela.com"

for more papers

If you aren4t confident doing any of these manipulations yourself, ask for helpQ 7t this stage you may want to reboot your system to make absolutely sure the new setting has taken effect. :ou probably won4t need to reboot for -indows .T, V or 2555. :ou can also avoid it in earlier versions by editing the file &!S-I.D,-+S&,**7.DS&*DI.IT.C7T instead of 7)T,AVA&.C7T. :ou should now be able to start a new command window, enter python at the &!> /or whatever1 prompt, and see the >>> prompt that indicates the ython interpreter is reading interactive commands. Pet4s suppose you have a program called pytest.py in directory &!S+teveS ro#ectsS ython. 7 session to run that program might look like this! &!S> cd S+teveS ro#ectsS ython &!S+teveS ro#ectsS ython> python pytest.py Cecause you added a file name to the command to start the interpreter, when it starts up it reads the ython script in the named file, compiles it, e%ecutes it, and terminates, so you see another &!S> prompt. :ou might also have entered &!S> python S+teveS ro#ectsS ythonSpytest.py if you hadn4t wanted to change your current directory. )nder .T, 2555 and V you may well find that the installation process has also arranged that the command pytest.py /or, if the file isn4t in the current directory, &!S+teveS ro#ectsS ythonSpytest.py1 will automatically recognize the 8.py8 e%tension and run the ython interpreter on the named file. )sing this feature is fine, but some versions of -indows have bugs which mean that this form isn4t e%actly e=uivalent to using the interpreter e%plicitly, so be careful. The important things to remember are! 1. +tart ython from the +tart *enu, or make sure the 7TI is set correctly so -indows can find the ython interpreter. python should give you a 4>>>8 prompt from the ython interpreter. Don4t forget the &TTP$] and A.TAT to terminate the interpreter /and, if you started the window from the +tart *enu, make the window disappear1. 2. ,nce this works, you run programs with commands! python 2program$file3 ?. -hen you know the commands to use you can build -indows shortcuts to run the ython interpreter on any of your scripts, naming particular working directories, and adding them to your menus. Take a look at 6isit

http!""www.downloadmela.com"

for more papers

python $$help if your needs are comple%. @. Interactive mode /where you see the >>> prompt1 is best used for checking that individual statements and e%pressions do what you think they will, and for developing code by e%periment.

How do I make python scripts executable? ,n -indows 2555, the standard ython installer already associates the .py e%tension with a file type / ython.(ile1 and gives that file type an open command that runs the interpreter /D!S rogram (ilesS ythonSpython.e%e 8R18 RD1. This is enough to make scripts e%ecutable from the command prompt as 4foo.py4. If you4d rather be able to e%ecute the script by simple typing 4foo4 with no e%tension you need to add .py to the 7TIAVT environment variable. ,n -indows .T, the steps taken by the installer as described above allow you to run a script with 4foo.py4, but a longtime bug in the .T command processor prevents you from redirecting the input or output of any script e%ecuted in this way. This is often important. The incantation for making a ython script e%ecutable under -in.T is to give the file an e%tension of .cmd and add the following as the first line! Wsetlocal enablee%tensions Y python $% R^f5 RD Y goto !A,( How do I debug an extension? -hen using MDC with dynamically loaded e%tensions, you can4t set a breakpoint in your e%tension until your e%tension is loaded. In your .gdbinit file /or interactively1, add the command! br G yImportGPoadDynamic*odule Then, when you run MDC! J gdb "local"bin"python gdb1 run myscript.py gdb1 continue < repeat until your e%tension is loaded gdb1 finish < so that your e%tension is loaded gdb1 br myfunction.c!U5 gdb1 continue Where is 7ree(e for Windows? 8(reeze8 is a program that allows you to ship a ython program as a single stand$alone e%ecutable file. It is not a compiler9 your programs don4t run any faster, but they are more easily distributable, at least to platforms with the same ,+ and & ). Is a 8+pyd file the same as a 399? 6isit

http!""www.downloadmela.com"

for more papers

:es, . How can I embed Python into a Windows application? Ambedding the ython interpreter in a -indows app can be summarized as follows! 1. Do GnotG build ython into your .e%e file directly. ,n -indows, ython must be a DPP to handle importing modules that are themselves DPP4s. /This is the first key undocumented fact.1 Instead, link to python...dll9 it is typically installed in &!S-indowsS+ystem. .. is the ython version, a number such as 82?8 for ython 2.?. :ou can link to ython statically or dynamically. Pinking statically means linking against python...lib, while dynamically linking means linking against python...dll. The drawback to dynamic linking is that your app won4t run if python...dll does not e%ist on your system. /Meneral note! python...lib is the so$called 8import lib8 corresponding to python.dll. It merely defines symbols for the linker.1 Pinking dynamically greatly simplifies link options9 everything happens at run time. :our code must load python...dll using the -indows PoadPibraryA%/1 routine. The code must also use access routines and data in python...dll /that is, ython4s & 7 I4s1 using pointers obtained by the -indows Met roc7ddress/1 routine. *acros can make using these pointers transparent to any & code that calls routines in ython4s & 7 I. Corland note! convert python...lib to ,*( format using &off2,mf.e%e first. 2. If you use +-IM, it is easy to create a ython 8e%tension module8 that will make the app4s data and methods available to ython. +-IM will handle #ust about all the grungy details for you. The result is & code that you link into your .e%e file /Q1 :ou do GnotG have to create a DPP file, and this also simplifies linking. ?. +-IM will create an init function /a & function1 whose name depends on the name of the e%tension module. (or e%ample, if the name of the module is leo, the init function will be called initleo/1. If you use +-IM shadow classes, as you should, the init function will be called initleoc/1. This initializes a mostly hidden helper class used by the shadow class. The reason you can link the & code in step 2 into your .e%e file is that calling the initialization function is e=uivalent to importing the module into ythonQ /This is the second key undocumented fact.1 @. In short, you can use the following code to initialize the ython interpreter with your e%tension module. <include 8python.h8 ... yGInitialize/19 "" Initialize ython. initmy7ppc/19 "" Initialize /import1 the helper class. yTunG+imple+tring/8import my7pp81 9 "" Import the shadow class. U. There are two problems with ython4s & 7 I which will become apparent if you use a compiler other 6isit

http!""www.downloadmela.com"

for more papers

than *+6&, the compiler used to build python...dll. roblem 1! The so$called 86ery Iigh Pevel8 functions that take (IPA D arguments will not work in a multi$compiler environment because each compiler4s notion of a struct (IPA will be different. (rom an implementation standpoint these are very GlowG level functions. roblem 2! +-IM generates the following code when generating wrappers to void functions! yGI.&TA(/ yG.one19 Gresultob# 0 yG.one9 return Gresultob#9 7las, yG.one is a macro that e%pands to a reference to a comple% data structure called G yG.one+truct inside python...dll. 7gain, this code will fail in a mult$compiler environment. Teplace such code by! return yGCuild6alue/8819 It may be possible to use +-IM4s Rtypemap command to make the change automatically, though I have not been able to get this to work /I4m a complete +-IM newbie1. H. )sing a ython shell script to put up a ython interpreter window from inside your -indows app is not a good idea9 the resulting window will be independent of your app4s windowing system. Tather, you /or the w% ython-indow class1 should create a 8native8 interpreter window. It is easy to connect that window to the ython interpreter. :ou can redirect ython4s i"o to GanyG ob#ect that supports read and write, so all you need is a ython ob#ect /defined in your e%tension module1 that contains read/1 and write/1 methods. How do I use Python for !/I? ,n the *icrosoft II+ server or on the -inKU *+ ersonal -eb +erver you set up ython in the same way that you would set up any other scripting engine. Tun regedt?2 and go to! IZA:GP,&7PG*7&II.AS+:+TA*S&urrent&ontrol+etS+ervicesS-?+6&S arametersS+cript*ap and enter the following line /making any specific changes that your system may need1! .py !TAMG+]! c!SSpython.e%e $u Rs Rs This line will allow you to call your script with a simple reference like! http!""yourserver"scripts"yourscript.py provided 8scripts8 is an 8e%ecutable8 directory for your server /which it usually is by default1. The 8$u8 flag specifies unbuffered and binary mode for stdin $ needed when working with binary data. In addition, it is recommended that using 8.py8 may not be a good idea for the file e%tensions when used in this conte%t /you might want to reserve D.py for support modules and use D.cgi or D.cgp for 6isit

http!""www.downloadmela.com"

for more papers

8main program8 scripts1. In order to set up Internet Information +ervices U to use ython for &MI processing, please see the following links! http!""www.e$coli.net"pyiisGserver.html /for -in2k +erver1 http!""www.e$coli.net"pyiis.html /for -in2k pro1 &onfiguring 7pache is much simpler. In the 7pache configuration file httpd.conf, add the following line at the end of the file! +criptInterpreter+ource Tegistry Then, give your ython &MI$scripts the e%tension .py and put them in the cgi$bin directory. How do I emulate os+kill%& in Windows? )se win?2api! def kill/pid1! 888kill function for -in?2888 import win?2api handle 0 win?2api.,pen rocess/1, 5, pid1 return /5 Q0 win?2api.Terminate rocess/handle, 511 Why does os+path+isdir%& fail on -) shared directories? The solution appears to be always append the 8S8 on the end of shared drives. >>> import os >>>os.path.isdir/ 4SSSSrorschachSSpublic41 5 >>>os.path.isdir/ 4SSSSrorschachSSpublicSS41 1 It helps to think of share points as being like drive letters. A%ample! k! is not a directory k!S is a directory k!Smedia is a directory k!SmediaS is not a directory The same rules apply if you substitute 8k!8 with 8Sconkyfoo8! SSconkySfoo is not a directory SSconkySfooS is a directory SSconkySfooSmedia is a directory SSconkySfooSmediaS is not a directory Web Python 6isit

http!""www.downloadmela.com"

for more papers

+ome host providers only let you run &MI scripts in a certain directory, often named cgi$bin. In this case all you have to do to run the script is to call it like this! http!""myGserver.tld"cgi$bin"myGscript.py The script will have to be made e%ecutable by 8others8. Mive it a OUU permission or check the e%ecutable bo%es if there is a graphical (T interface. +ome hosts let you run &MI scripts in any directory. In some of these hosts you don4t have to do anything do configure the directories. In others you will have to add these lines to a file named .htaccess in the directory you want to run &MI scripts from! ,ptions 'A%ec&MI 7ddIandler cgi$script .py If the file does not e%ist create it. 7ll directories below a directory with a .htaccess file will inherit the configurations. +o if you want to be able to run &MI scripts from all directories create this file in the document root. To run a script saved at the root! http!""myGserver.tld"myGscript.py If it was saved in some directory! http!""myGserver.tld"someGdir"someGsubdir"myGscript.py *ake sure all te%t files you upload to the server are uploaded as te%t /not binary1, specially if you are in -indows, otherwise you will have problems. )he classical "Hello World" in python !/I fashion# <Q"usr"bin"env python print 8&ontent$Type! te%t"html8 print print 888S Nhtml> Nbody> Nh2>Iello -orldQ N"body> N"html> 888 To test your setup save it with the .py e%tension, upload it to your server as te%t and make it e%ecutable before trying to run it. The first line of a python &MI script sets the path where the python interpreter will be found in the 6isit

http!""www.downloadmela.com"

for more papers

server. 7sk your provider what is the correct one. If it is wrong the script will fail. +ome e%amples! <Q"usr"bin"python <Q"usr"bin"python2.? <Q"usr"bin"python2.@ It is necessary that the script outputs the ITT header. The ITT header consists of one or more messages followed by a blank line. If the output of the script is to be interpreted as IT*P then the content type will be te%t"html. The blank line signals the end of the header and is re=uired. print 8&ontent$Type! te%t"html8 print If you change the content type to te%t"plain the browser will not interpret the script4s output as IT*P but as pure te%t and you will only see the IT*P source. Try it now to never forget. 7 page refresh may be necessary for it to work. &lient versus +erver 7ll python code will be e%ecuted at the server only. The client4s agent /for e%ample the browser1 will never see a single line of python. Instead it will only get the script4s output. This is something realy important to understand. -hen programming for the -eb you are in a client$server environment, that is, do not make things like trying to open a file in the client4s computer as if the script were running there. It isn4t. How to 3ebugging in python? +ynta% and header errors are hard to catch unless you have access to the server logs. +ynta% error messages can be seen if the script is run in a local shell before uploading to the server. (or a nice e%ceptions report there is the cgitb module. It will show a traceback inside a conte%t. The default output is sent to standard output as IT*P! <Q"usr"bin"env python print 8&ontent$Type! te%t"html8 print import cgitb9 cgitb.enable/1 print 1"5 The handler/1 method can be used to handle only the catched e%ceptions! <Q"usr"bin"env python print 8&ontent$Type! te%t"html8 print import cgitb try! f 0 open/4non$e%istent$file.t%t4, 4r41 6isit

http!""www.downloadmela.com"

for more papers

e%cept! cgitb.handler/1 There is also the option for a crude approach making the header 8te%t"plain8 and setting the standard error to standard out! <Q"usr"bin"env python print 8&ontent$Type! te%t"plain8 print import sys sys.stderr 0 sys.stdout f 0 open/4non$e%istent$file.t%t4, 4r41 -ill output this! Traceback /most recent call last1! (ile 8"var"www"html"teste"cgi$bin"te%tGerror.py8, line H, in ; f 0 open/4non$e%istent$file.t%t4, 4r41 I,Arror! EArrno 2F .o such file or directory! 4non$e%istent$file.t%t4 -arning! These techni=ues e%pose information that can be used by an attacker. )se it only while developing"debugging. ,nce in production disable it. How to make 7orms in python? The (ield+torage class of the cgi module has all that is needed to handle submited forms. import cgi form 0 cgi.(ield+torage/1 < instantiate only onceQ It is transparent to the programmer if the data was submited by MAT or by ,+T. The interface is e%actly the same. D )ni=ue field names ! +uppose we have this IT*P form which submits a field named name to a python &MI script named processGform.py! Nhtml>Nbody> Nform method08get8 action08processGform.py8> .ame! Ninput type08te%t8 name08name8> Ninput type08submit8 value08+ubmit8> N"form> N"body>N"html> This is the processGform.py script!

6isit

http!""www.downloadmela.com"

for more papers

<Q"usr"bin"env python import cgi form 0 cgi.(ield+torage/1 < instantiate only onceQ name 0 form.getfirst/4name4, 4empty41 < 7void script in#ection escaping the user input name 0 cgi.escape/name1 print 888S &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>The submited name was 8Rs8N"p> N"body>N"html> 888 R name The getfirst/1 method returns the first value of the named field or a default or .one if no field with that name was submited or if it is empty. If there is more than one field with the same name only the first will be returned. If you change the IT*P form method from get to post the processGform.py script will be the same. D *ultiple field names! If there is more than one field with the same name like in IT*P input check bo%es then the method to be used is getlist/1. It will return a list containing as many items /the values1 as checked bo%es. If no check bo% was checked the list will be empty. +ample IT*P with check bo%es! Nhtml>Nbody> Nform method08post8 action08processGcheck.py8> TedNinput type08checkbo%8 name08color8 value08red8> MreenNinput type08checkbo%8 name08color8 value08green8> Ninput type08submit8 value08+ubmit8> N"form> N"body>N"html> 7nd the corresponding processGcheck.py script! <Q"usr"bin"env python import cgi form 0 cgi.(ield+torage/1 < getlist/1 returns a list containing the < values of the fields with the given name colors 0 form.getlist/4color41 6isit

http!""www.downloadmela.com"

for more papers

print 8&ontent$Type! te%t"htmlSn8 print 4Nhtml>Nbody>4 print 4The colors list!4, colors for color in colors! print 4Np>4, cgi.escape/color1, 4N"p>4 print 4N"body>N"html>4 D (ile )pload9 To upload a file the IT*P form must have the enctype attribute set to multipart"form$data. The input tag with the file type will create a 8Crowse8 button. Nhtml>Nbody> Nform enctype08multipart"form$data8 action08saveGfile.py8 method08post8> Np>(ile! Ninput type08file8 name08file8>N"p> Np>Ninput type08submit8 value08)pload8>N"p> N"form> N"body>N"html> The getfirst/1 and getlist/1 methods will only return the file/s1 content. To also get the filename it is necessary to access a nested (ield+torage instance by its inde% in the top (ield+torage instance. <Q"usr"bin"env python import cgi form 0 cgi.(ield+torage/1 < 7 nested (ield+torage instance holds the file fileitem 0 formE4file4F < Test if the file was uploaded if fileitem.filename! open/4files"4 ' fileitem.filename, 4w41.write/fileitem.file.read/11 message 0 4The file 84 ' fileitem.filename ' 48 was uploaded successfully4 else! message 0 4.o file was uploaded4 print 888S &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>RsN"p> N"body>N"html> 888 R /message,1 The 7pache user must have write permission on the directory where the file will be saved.

6isit

http!""www.downloadmela.com"

for more papers

D Cig (ile )pload To handle big files without using all the available memory a generator can be used. The generator will return the file in small chunks! <Q"usr"bin"env python import cgi form 0 cgi.(ield+torage/1 < Menerator to buffer file chunks def fbuffer/f, chunkGsize0155551! while True! chunk 0 f.read/chunkGsize1 if not chunk! break yield chunk < 7 nested (ield+torage instance holds the file fileitem 0 formE4file4F < Test if the file was uploaded if fileitem.filename! f 0 open/4files"4 ' fileitem.filename, 4w41 < Tead the file in chunks for chunk in fbuffer/fileitem.file1! f.write/chunk1 f.close/1 message 0 4The file 84 ' fileitem.filename ' 48 was uploaded successfully4 else! message 0 4.o file was uploaded4 print 888S &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>RsN"p> N"body>N"html> 888 R /message,1 How to use !ookies for Web python ? ITT is said to be a stateless protocol. -hat this means for web programmers is that every time a user loads a page it is the first time for the server. The server can4t say whether this user has ever visited that site, if is he in the middle of a buying transaction, if he has already authenticated, etc. 7 cookie is a tag that can be placed on the user4s computer. -henever the user loads a page from a site the site4s script can send him a cookie. The cookie can contain anything the site needs to identify that user. Then within the ne%t re=uest the user does for a new page there goes back the cookie with all the 6isit

http!""www.downloadmela.com"

for more papers

pertinent information to be read by the script. D +et the &ookie9 There are two basic cookie operations. The first is to set the cookie as an ITT header to be sent to the client. The second is to read the cookie returned from the client also as an ITT header. This script will do the first one placing a cookie on the client4s browser! <Q"usr"bin"env python import time < This is the message that contains the cookie < and will be sent in the ITT header to the client print 4+et$&ookie! lastvisit04 ' str/time.time/119 < To save one line of code < we replaced the print command with a 4Sn4 print 4&ontent$Type! te%t"htmlSn4 < And of ITT header print 4Nhtml>Nbody>4 print 4+erver time is4, time.asctime/time.localtime/11 print 4N"body>N"html>4 The +et$&ookie header contains the cookie. +ave and run this code from your browser and take a look at the cookie saved there. +earch for the cookie name, lastvisit, or for the domain name, or the server I like 15.1.1.1 or 12O.5.5.1. The &ookie ,b#ect The &ookie module can save us a lot of coding and errors and the ne%t pages will use it in all cookie operations. <Q"usr"bin"env python import time, &ookie < Instantiate a +imple&ookie ob#ect cookie 0 &ookie.+imple&ookie/1 < The +imple&ookie instance is a mapping cookieE4lastvisit4F 0 str/time.time/11 < ,utput the ITT message containing the cookie print cookie print 4&ontent$Type! te%t"htmlSn4 6isit

http!""www.downloadmela.com"

for more papers

print 4Nhtml>Nbody>4 print 4+erver time is4, time.asctime/time.localtime/11 print 4N"body>N"html>4 It does not seem as much for this e%tremely simple code, but wait until it gets comple% and the &ookie module will be your friend. D Tetrieve the &ookie9 The returned cookie will be available as a string in the os.environ dictionary with the key 4ITT G&,,ZIA4! cookieGstring 0 os.environ.get/4ITT G&,,ZIA41 The load/1 method of the +imple&ookie ob#ect will parse that string rebuilding the ob#ect4s mapping! cookie.load/cookieGstring1 &omplete code! <Q"usr"bin"env python import &ookie, os, time cookie 0 &ookie.+imple&ookie/1 cookieE4lastvisit4F 0 str/time.time/11 print cookie print 4&ontent$Type! te%t"htmlSn4 print 4Nhtml>Nbody>4 print 4Np>+erver time is4, time.asctime/time.localtime/11, 4N"p>4 < The returned cookie is available in the os.environ dictionary cookieGstring 0 os.environ.get/4ITT G&,,ZIA41 < The first time the page is run there will be no cookies if not cookieGstring! print 4Np>(irst visit or cookies disabledN"p>4 else! < Tun the page twice to retrieve the cookie print 4Np>The returned cookie string was 84 ' cookieGstring ' 48N"p>4 < load/1 parses the cookie string cookie.load/cookieGstring1 < )se the value attribute of the cookie to get it 6isit

http!""www.downloadmela.com"

for more papers

lastvisit 0 float/cookieE4lastvisit4F.value1 print 4Np>:our last visit was at4, print time.asctime/time.localtime/lastvisit11, 4N"p>4 print 4N"body>N"html>4 -hen the client first loads the page there will be no cookie in the client4s computer to be returned. The second time the page is re=uested then the cookie saved in the last run will be sent to the server. D *orsels In the previous cookie retrieve program the lastvisit cookie value was retrieved through its value attribute! lastvisit 0 float/cookieE4lastvisit4F.value1 -hen a new key is set for a +imple&ookie ob#ect a *orsel instance is created! >>> import &ookie >>> import time >>> >>> cookie 0 &ookie.+imple&ookie/1 >>> cookie N+imple&ookie! > >>> >>> cookieE4lastvisit4F 0 str/time.time/11 >>> cookieE4lastvisit4F N*orsel! lastvisit0411UKU?U1??.??4> >>> >>> cookieE4lastvisit4F.value 411UKU?U1??.??4 Aach cookie, a *orsel instance, can only have a predefined set of keys! e%pires, path, commnent, domain, ma%$age, secure and version. 7ny other key will raise an e%ception. <Q"usr"bin"env python import &ookie, time cookie 0 &ookie.+imple&ookie/1 < name"value pair cookieE4lastvisit4F 0 str/time.time/11 < e%pires in % seconds after the cookie is output. < the default is to e%pire when the browser is closed 6isit

http!""www.downloadmela.com"

for more papers

cookieE4lastvisit4FE4e%pires4F 0 ?5 D 2@ D H5 D H5 < path in which the cookie is valid. < if set to 4"4 it will valid in the whole domain. < the default is the script4s path. cookieE4lastvisit4FE4path4F 0 4"cgi$bin4 < the purpose of the cookie to be inspected by the user cookieE4lastvisit4FE4comment4F 0 4holds the last userS4s visit date4 < domain in which the cookie is valid. always stars with a dot. < to make it available in all subdomains < specify only the domain like .myGsite.com cookieE4lastvisit4FE4domain4F 0 4.www.myGsite.com4 < discard in % seconds after the cookie is output < not supported in most browsers cookieE4lastvisit4FE4ma%$age4F 0 ?5 D 2@ D H5 D H5 < secure has no value. If set directs the user agent to use < only /unspecified1 secure means to contact the origin < server whenever it sends back this cookie cookieE4lastvisit4FE4secure4F 0 44 < a decimal integer, identifies to which version of < the state management specification the cookie conforms. cookieE4lastvisit4FE4version4F 0 1 print 4&ontent$Type! te%t"htmlSn4 print 4Np>4, cookie, 4N"p>4 for morsel in cookie! print 4Np>4, morsel, 404, cookieEmorselF.value print 4Ndiv style08margin!$1em auto auto ?em98>4 for key in cookieEmorselF! print key, 404, cookieEmorselFEkeyF, 4Nbr ">4 print 4N"div> 4 .otice that print cookie automatically formats the e%pire date.

How to use 'essions for Web python ? +essions are the server side version of cookies. -hile a cookie persists data /or state1 at the client, 6isit

http!""www.downloadmela.com"

for more papers

sessions do it at the server. +essions have the advantage that the data do not travel the network thus making it both safer and faster although this not entirely true as shown in the ne%t paragraph The session state is kept in a file or in a database at the server side. Aach session is identified by an id or session id /+ID1. To make it possible to the client to identify himself to the server the +ID must be created by the server and sent to the client and then sent back to the server whenever the client makes a re=uest. There is still data going through the net, the +ID. The server can send the +ID to the client in a link4s =uery string or in a hidden form field or as a +et$ &ookie header. The +ID can be sent back from the client to the server as a =uery string parameter or in the body of the ITT message if the post method is used or in a &ookie ITT header. If a cookie is not used to store the +ID then the session will only last until the browser is closed, or the user goes to another site breaking the ,+T or =uery string transmission, or in other words, the session will last only until the user leaves the site. D &ookie Cased +ID! 7 cookie based session has the advantage that it lasts until the cookie e%pires and, as only the +ID travels the net, it is faster and safer. The disadvantage is that the client must have cookies enabled. The only particularity with the cookie used to set a session is its value! < The sid will be a hash of the server time sid 0 sha.new/repr/time.time/111.he%digest/1 The hash of the server time makes an uni=ue +ID for each session. <Q"usr"bin"env python import sha, time, &ookie, os cookie 0 &ookie.+imple&ookie/1 stringGcookie 0 os.environ.get/4ITT G&,,ZIA41 < If new session if not stringGcookie! < The sid will be a hash of the server time sid 0 sha.new/repr/time.time/111.he%digest/1 < +et the sid in the cookie cookieE4sid4F 0 sid < -ill e%pire in a year cookieE4sid4FE4e%pires4F 0 12 D ?5 D 2@ D H5 D H5 < If already e%istent session else! cookie.load/stringGcookie1 6isit

http!""www.downloadmela.com"

for more papers

sid 0 cookieE4sid4F.value print cookie print 4&ontent$Type! te%t"htmlSn4 print 4Nhtml>Nbody>4 if stringGcookie! print 4Np>7lready e%istent sessionN"p>4 else! print 4Np>.ew sessionN"p>4 print 4Np>+ID 04, sid, 4N"p>4 print 4N"body>N"html>4 In every page the e%istence of the cookie must be tested. If it does not e%ist then redirect to a login page or #ust create it if a login or a previous state is not re=uired. D Xuery +tring +ID9 Xuery string based session! <Q"usr"bin"env python import sha, time, cgi, os sid 0 cgi.(ield+torage/1.getfirst/4sid41 if sid! < If session e%ists message 0 47lready e%istent session4 else! < .ew session < The sid will be a hash of the server time sid 0 sha.new/repr/time.time/111.he%digest/1 message 0 4.ew session4 =s 0 4sid04 ' sid print 888S &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>RsN"p> Np>+ID 0 RsN"p> Np>Na href08."setGsidG=s.py;sid0Rs8>reloadN"a>N"p> N"body>N"html> 888 R /message, sid, sid1 To mantain a session you will have to append the =uery string to all the links in the page.

6isit

http!""www.downloadmela.com"

for more papers

+ave this file as setGsidG=s.py and run it two or more times. Try to close the browser and call the page again. The session is gone. The same happens if the page address is typed in the address bar. D Iidden (ield +ID9 The hidden form field +ID is almost the same as the =uery string based one, sharing the same problems. <Q"usr"bin"env python import sha, time, cgi, os sid 0 cgi.(ield+torage/1.getfirst/4sid41 if sid! < If session e%ists message 0 47lready e%istent session4 else! < .ew session < The sid will be a hash of the server time sid 0 sha.new/repr/time.time/111.he%digest/1 message 0 4.ew session4 =s 0 4sid04 ' sid print 888S &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>RsN"p> Np>+ID 0 RsN"p> Nform method08post8> Ninput type08hidden8 name0sid value08Rs8> Ninput type08submit8 value08+ubmit8> N"form> N"body>Nhtml> 888 R /message, sid, sid1 D The shelve module9 Iaving a +ID is not enough. It is necessary to save the session state in a file or in a database. To save it into a file the shelve module is used. The shelve module opens a file and returns a dictionary like ob#ect which is readable and writable as a dictionary. < The shelve module will persist the session data < and e%pose it as a dictionary session 0 shelve.open/4"tmp".session"sessG4 ' sid, writeback0True1

6isit

http!""www.downloadmela.com"

for more papers

The +ID is part of file name making it a uni=ue file. The apache user must have read and write permission on the file4s directory. HH5 would be ok. The values of the dictionary can be any ython ob#ect. The keys must be immutable ob#ects. < +ave the current time in the session sessionE4lastvisit4F 0 repr/time.time/11 < Tetrieve last visit time from the session lastvisit 0 session.get/4lastvisit41 The dictionary like ob#ect must be closed as any other file should be! session.close/1 D &ookie and +helve9 7 sample of how to make cookies and shelve work together keeping session state at the server side! <Q"usr"bin"env python import sha, time, &ookie, os, shelve cookie 0 &ookie.+imple&ookie/1 stringGcookie 0 os.environ.get/4ITT G&,,ZIA41 if not stringGcookie! sid 0 sha.new/repr/time.time/111.he%digest/1 cookieE4sid4F 0 sid message 0 4.ew session4 else! cookie.load/stringGcookie1 sid 0 cookieE4sid4F.value cookieE4sid4FE4e%pires4F 0 12 D ?5 D 2@ D H5 D H5 < The shelve module will persist the session data < and e%pose it as a dictionary session 0 shelve.open/4"tmp".session"sessG4 ' sid, writeback0True1 < Tetrieve last visit time from the session lastvisit 0 session.get/4lastvisit41 if lastvisit! message 0 4-elcome back. :our last visit was at 4 ' S time.asctime/time.gmtime/float/lastvisit111 < +ave the current time in the session sessionE4lastvisit4F 0 repr/time.time/11 6isit

http!""www.downloadmela.com"

for more papers

print 888S Rs &ontent$Type! te%t"htmlSn Nhtml>Nbody> Np>RsN"p> Np>+ID 0 RsN"p> N"body>N"html> 888 R /cookie, message, sid1 session.close/1 It first checks if there is a cookie already set. If not it creates a +ID and attributes it to the cookie value. 7n e%piration time of one year is established. The lastvisit data is what is maintained in the session.

6isit

http!""www.downloadmela.com"

for more papers