Role Of Transgenic Animal In Target Validation-1.pptx
Python Tutorial for Beginner
1. Tutorial on Python Programming
Second Floor and Third Floor,
5/3 BEML Layout,
Varathur Road,
Thubarahalli,
Kundalahalli Gate,
Bangalore 66
Landmark – Behind Kundalahalli Gate bus stop,
Opposite to SKR Convention Mall,
Next to AXIS Bank.
2. AboutTIBAcademy
TIB Academy Provides Python Training in Bangalore with Best
Python Experts / Experienced professionals in Automobile
industries, Electronics Robotics Industries, Software Service
providers and many more. TIB Academy in Bangalore offers the
best Python training in Bangalore, like basic Python for
beginners and laterals, Machine Learning and Data Science for
senior experienced professionals and Django framework for
those interested. Apart from Python, TIB offers software
training for many other courses to step into MNCs and Top
Corporates. TIB can help you choose your career path as
Developer, Tester or Admin. And within Developer, you can
choose to be a frontend developer or backend developer or BI
developer or Mobile App developer and there are several other
career paths to choose from.
3. Python - What, Why and How?
• Python is apowerful scriptinglanguage created by Guido Van
Rossum in 1998.
• Python in itself is afeature rich, object oriented language and can
be used for Rapid Application Development of medium sized
applications.
• Python is ascriptinglanguage of choice of alarge number of the
security professionals, developersand automation engineers. There
isan ever-growingcommunity supportingPython.
• You can get Python asafree download from Official Python website
or asActivePython from ActiveState website. There are other
versionsavailable, but the mentioned onessolve the purpose.
4. Python Features…• It is free and open source.
• Easy coding- It'smeant for Rapid application development.
Consistent style of codingand usage make your life easier than
rememberingsome 100 shortcutsor tricks.
• Excellent Readability and Maintainability - Proper Indentation of
code is not achoice, rather the way of Python coding. If you pick
Python code by different programmers, you can be sure to see
similar lookingcode.
• It is Object-oriented - OOPis not apatch work for Python, rather an
in-built feature.
• Python include the use of transparent byte-code compilation
for speed, automaticmemory management and garbage
collection, and avery powerful object oriented and modular
design.
5. • Python shipswith alarge number of modules.
• No semi-intelligence - No ambiguoustype-conversionsor
assumptions.
• Exception Handlingis built into the language.
• It is CrossPlatform compatible.
6. Syllabus
Introduction
Execution steps
Memory management and Garbage collections
Data Types and Operations
Statements and Syntax
File Operations and Functions
Modules and Packages
Classes and Exceptional Handling
Advanced Concepts
Standard Library Modules
References
Exercises
Roadmap with Python
7. Command Line Arguments
• Sysmodule comesto the rescue.
• Import sys
• Print sys.argv[0]
• For i in sys.argv[]:
print i
• The type of all the command line argumentsis str.
• Checkingfor input datatypesand type conversion should alwaysbe
done.
8. Python Interpreter
• Executinginteractively: Open DOSprompt and just type python.
• C:>python ActivePython 2.5.1.1 (ActiveState Software Inc.) based
on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSCv.1310
32 bit (Intel)] on win32 Type "help", "copyright", "credits" or
"license" for more information. >>>
• >>> print "Welcome to Technobeans!" Welcome to Technobeans!
• To come out of the interactive shell, pressCtrl+Zand Enter key.
• When Python interpreter loads, modules/packageswill be available
for importing <Python installation>libsite-packages.
• sys.path.append("C: My_Scripts") – for importinguser
defined modules.
9. .pycand .pyo
• Python source code is automatically compiled into Python byte
code by the CPython interpreter. Compiled code is usually stored in
PYC(or PYO) files, and isregenerated when the source isupdated,
or when otherwise necessary.
• Automatic compilation – importingamodule. But the module gets
executed.
• Explicit compilation – py_compile.compile(“module.py”) –
generatesmodule.pyc
• When the Python interpreter is invoked with the -Oflag, optimized
code is generated and stored in ‘.pyo’ files.
• Passingtwo -Oflagsto the Python interpreter (-OO) will cause the
bytecode compiler to perform optimizationsthat could in some rare
casesresult in malfunctioningprograms.
10. • Aprogram doesn't run any faster when it is read from
a‘.pyc’ or ‘.pyo’ file than when it is read from a‘.py’ file; the only
thingthat'sfaster about ‘.pyc’ or‘.pyo’ filesisthe speed with which
they are loaded.
• When ascript is run by givingitsname on the command line, the
bytecode for the script is never written to a‘.pyc’ or ‘.pyo’ file. Thus,
the startup time of ascript may be reduced by movingmost of its
code to amodule and havingasmall bootstrap script that imports
that module. It is also possible to name a‘.pyc’ or ‘.pyo’ file directly
on the command line.
• The module ‘compileall’{} can create ‘.pyc’ files(or ‘.pyo’ fileswhen -
Ois used) for all modulesin adirectory.
• To distribute aprogram to people who already have Python
installed, you can ship either the PYfilesor the PYCfiles.
• Convert - .py to .exe ->Py2exe helps.
11. Datatypesavailable in Python
• The important (or rather the most commonly used) base data types
in Python are Numeric Types (numbers - int, long, float), Sequence
Types(string, list, tuple),Mapping Types(dictionary)
and Boolean(True/ False).
• For user-defined types, one hasto declare aclass.
• Out of the mentioned types, we will discussall the Numeric
Types, string(Sequence Type) and Boolean. Otherswill be
diccussed once we have learnt control structuresand some
built-in functions. The stringdatatype will be revisited as
well.
12. Declare avariable of aparticular type?
• ‘=‘ operator is the key.
• You do not have to use any special definingmethods. You simply
say: var_name =literal, where var_name is the name you choose
for variable and literal is aconstant value of any datatype.
• What’spresnet to the right definesthe type of LHSvariable name.
Everythingin Python is an object. Python findsthe type of a
variable from the value to which points.
• Also, because there is no strict definingstyle, you can point
var_name to any other literal of adifferent datatype.
13. How do I find the data type
• 2 waysof doingit:
– Type()
– Isinstance(variable, type)
Var =34
Print type(var)
if isinstance(var, int):
print True
14. GettingUser Input
• raw_input() function is used.
• Python acceptswhatever the end user typestill he or she presses
the “Enter” key, asan input and assignsit to the variable on left
side of the assignment.
• >>> a_var =raw_input("Please enter your name:")
Pleaseenter your name:Tester
>>> a_var 'Tester' >>>
• Whatever comesfrom STDINisalwaysastream of characters.
In your program, you have to convert the stringto the type
you want and in case of conversion error, inform the user
about the incorrectness.
• None asNOInput?
15. None, Empty!!
• Def foo():
pass
print foo() - None
• list =[]
for i in list:
print i - Empty
• a=raw_input(“enter a:”)
press“enter key” - Empty/ Sometimesreferred asNothing
• None is commonly used for exception handling.
16. Documentation Strings
• The first line should alwaysbe ashort, concise summary of the
object’spurpose.
• If there are more linesin the documentation string, the second line
should be blank, visually separatingthe summary from the rest of
the description.
• def example():
“””This is just an example.
It doessomething. “””
print “In example”
• print example. doc
18. Operators
• Greater than: >
• Lessthan: <
• Greater than or equal to: >=
• Lessthan or equal to: ⇐
• Equal to: ==
• Not equal to: <>!=
19. Conditional Execution
if / if-else / if-elif-if
• if condition1:
if condition2:
True path
else:
Falsepath
else:
Falsepath
20. LoopingExecution - while / for
• while condition
: Statements
• for var_name in Sequence/function which outputsa
sequence: statements
Range() - iterate over asequence of numbers.
range(5) =[0,1,2,3,4]
range(5,10) =[5,6,7,8,9]
range(0,10,3) =[0,3,6,9]
• Do-while: Not
available. While True:
if condition:
break
21. Break, Continue and Pass
• Break: The loop in which this statement is found exitsassoon asit
isreached. The control then jumpsto the outer loop in case of
nested loopsor to the main script.
• Continue: The loop in which this statement is found skipsrest of
the statementsfound after this, in itsbody. The control then jumps
to the beginningof the same loop and the next iteration is started.
• Pass:The passstatement doesnothing. It can be used asa
place-holder for afunction or conditional body when you are
workingon new code.
22. Sequence datatype
• ASequence type in python isamini built-in datastructurethat contains
elementsin an orderly manner which can be fetched usingindices. There
arethree typesof sequences:
• Stringsand tuplesare immutable in Python, but listsare mutable. (An
immutable object can not modified-in-place. What it meansisthat when a
function/expression triesto modify itscontentsright there itsoriginal
memorylocation, it either failsor createsan altogether new object.).
>>> a_string[0] ="t“ - Invalid
>>> a_list[0] ="My Example“ - Valid
>>> a_tuple[0] ="My Example“ - Invalid
Strings >>
>
a_string = “Chetan Giridhar"
Lists >>> a_list = [“Chetan",”Giridhar"]
Tuples >>> a_tuple =
(“Chetan",”Giridhar")
23. Operator Overloading
Python supportsoperator overloading.
• Indexing- Gettingan element with the help of an integer index.
• Slicing- Gettingasub-sequenceby usinga special syntaxof lower and
upper index.
• Appending/Extending/Concatenating- Addingelementsat the end of a
sequence.
• Deletingan element - For first occurrence.
• Modifyingan element - At agiven index.
• Sorting- Based on element types.
24. Workingwith lists
• Defininglists
numList =[2003,2005,2008,2010]
strList =[“IIA”, “Chetan”, “Python”]
• Accessingalist
For x in numList:
print x
print strList[0] or strList[-1]
• Slicingalist
firstHalf =numList[:2]
lastHalf =numList[2:3]
• Addingand removingitems
list.append(“2009”) – end of the list
list.extend(list1) – end of the list
list.insert(index, item) – at aspecified index
25. Pop(index) – removesthe element at the index
remove(item) – removesthe first occurrence of item.
• Sortingalist
list.sort()
list.reverse()
list =["iia","IIA", "chetan", "python"]
list.sort(key =str.lower)
for i in list:
print I
• Convertingtuple to
list List(tuple)
26. Stringfunctions• test =‘This is asimple string’
• len(test) =23
• test.count(‘r’) =1
• test.find(‘r’) =18
• test =test.replace(‘simple’, ‘short’)
‘This is short string’
• test.index(‘simple’) =10
• test.split(‘is’) =[‘This ‘, ‘ashort string’]
• ‘some’. join(test.split(‘is’))
• test.upper() and test.lower() and test.lower.capatalize()
• test.lstrip(‘ ‘) and test.rstrip(‘t’)
27. eval vsexec
• Execfunction will execute Python Code that is contained in str
stringand return the result.
• Eval workssimilar to the exec function except that it only evaluates
the stringasPython expression and returnsthe result.
• def foo():
print "foo“
eval("foo" +"()")
• cards=['king', 'queen', 'jack']
codeStr ="for i in cards:
print i"
exec(codeStr)
28. What isaPython dictionary?
• APython dictionary is aMapping Type, which is amini data-
structure, containingkey-value pairs.
• Adictionary hasunsorted key-value pairs. It meansthe datain
adictionary is not in any necessary order, unlike asequence type.
This helpsto give Python, alot of freedom in termsof memory
management.
• The key in adictionary should be immutable.
• Akey is alwaysunique. If you use the same key in an assignment,
the value of this key getsupdated, instead of addinganew key with
the same name.
30. Code Reusability in Python
• Implementing code reusability happensthrough the use of
functions, modulesand packages.
• You write the code in generic ways to come up with functions, pack
related functions in a single module (file) and pack multiple related
modulesinside apackage (directory structure).
• Another form of the above is that you write methods(functions)
that belongto aclass(that signifiesauser defined datatype), put
related classesinsideamodule, put related modulesinside a
package.
• Everythingis an object in Python. It would make sense that you
create an object (of aclass) to talk to another object (built on or
your own) rather than codingin the traditional way while beingin
the world of awonderful OOlanguage like Python.
31. Workingwith functions
• Atypical function
def multiply(operand1,operand2):
return a* b
The above isafunction with name multiply. What it doesis, it takestwo
argumentsand returnsthe product of them.
Here operand1 and operand2are formal parameters. Notethat we did
not define their type in the function definition. So it becomesthe
responsibility of the function body to do typechecking.
The execution of afunction introducesanew symbol table used for the
local variablesof the function. Moreprecisely, all variable assignments
in afunction store the value in the local symbol table; whereasvariable
referencesfirst look in the local symbol table, then in the global
symbol table, and then in the table of built-in names. LGBisthe
mantra.
Default valuescan be used and passed.
32. Scopingof variables
• In Python, variablesthat are only referenced inside afunction are
implicitly global. If avariable is assigned anew value anywhere
within the function'sbody, it'sassumed to be alocal. If avariable is
ever assigned anew value insidethe function, the variable is
implicitly local, and you need to explicitly declare it as'global'.
• Though abit surprisingat first, amoment'sconsideration explains
this. On one hand, requiringglobal for assigned variablesprovidesa
bar against unintended side-effects. On the other hand, if global
wasrequired for all global references, you'd be usingglobal all the
time. You'd have to declare asglobal every reference to abuilt-in
function or to acomponent of an imported module. This clutter
would defeat the usefulnessof the global declaration for identifying
side-effects.
33. Rules– makingafunction call
1. Number of arguments- Number of argumentsshould be equal to
the number of formal parametersused in the definition of the
function.
2. Type of arguments- The argument and the corresponding
parameter should have the same datatype.
3. Order of arguments- The argumentsshould have the same order
asthat of the formal parameters, otherwise you might get type
mismatch errorsor unexpected resultsin some cases.
Example:
>>>def printData(name, age):
return "Name: %sAge: %d" %(name,age)
>>> printData("Tester",100) 'Name: Tester Age: 100
if you carefully see the stringformatting used, %sand %d format
specifiersmake Python take care of type checkingautomatically.
34. PassBy – Value and reference
• Parametersare passed by value.
• Stringsand Tuplesare immutable and hence cant be changed.
• When listsare passed, they get muted and hence it looksasif they
are gettingpassed by references.
35. Lambda – Anonymousfunctions
• Anonymousfunctions: functionsthat are not bound to aname at
run time.
• g=lambda x: x**2
g(8) – 64
• Lambdadefinition doesnot include a"return" statement -- it
alwayscontainsan expression which isreturned.
• def make_incrementor (n): return lambdax: x +n
The above code defines a function "make_inrementor" that
createsan anonymousfunction on the fly and returnsit. The
returned function incrementsitsargument by the value that
wasspecified when it wascreated.
• f =make_incrementor(2) . f(42) =44.
37. File Handling
• open(filename, mode)
>>> f =open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
Modes: r, w, a, b, r+, rb, wb, r+b
• f.read(size)
When sizeisomitted or negative, the entire contentsof the file will
be read and returned;
If the end of the file hasbeen reached, f.read() will return an empty
string("").
• f.readline() readsa single line from the file; a newline character (n)
is left at the end of the string, and is only omitted on the last line of
the file if the file doesn’t end in anewline.
38. • f.readlines() returnsalist containingall the linesof datain the file.
If given an optional parameter sizehint, it readsthat many bytes
from the file and enough more to complete aline, and returnsthe
linesfrom that.
• Read words: Memory efficient, fast, and simpler code:
for line in f:
print line ORfor word in line.split()
• f.write(string) writesthe contentsof string to the file,
returningNone. To write somethingother than astring, it needsto
be converted to astringfirst.
• f.tell() returnsan integer givingthe file object’scurrent position in
the file, measured in bytesfrom the beginningof the file.
• To change the file object’sposition, use f.seek(offset, from_what).
• f.close() to close it and free up any system resourcestaken up by
the open file.
• F.endswitch(“py”) search for fileswith extension py – True/False
39. Some more file operations
• Import os
• os.remove(filepath)
• os.rename(oldzfile, newFile)
• os.listdir(dirPath)
• os.walk(dirPath)
40. Pickling
• Way to achieve object serialization in Python.
• Picklingisused when you want to save morecomplexdatatypeslike lists,
dictionaries, or classinstancesin afile.
• Dumpingand parsinglogicisdifficult to develop and maintain.
• Python cPickle module can take almost any Python object and
convert it to astringrepresentation; this processis called pickling.
• pickle is the standard way to make Python objectswhich can be
stored and reused by other programsor by afuture invocation of
the same program
• Reconstructingthe object from the stringrepresentation is
called unpickling.
• Between picklingand unpickling, the stringrepresentingthe object
may have been stored in afile or data, or sent over anetwork
connection to some distant machine.
• If you have an object x, and afile object f that’sbeen opened for
writing, the simplest way to pickle and unpickle the object is:
pickle.dump(x, f) and x =pickle.load(f).
41. Some Concepts
• code block: Acode block is apiece of Python program text that can
be executed asaunit, such asamodule, aclassdefinition or a
function body.
• Execution frame: Every code block is assigned an execution frame
by Python.
1.Python maintainssome debugginginformation about the code
block asapart of the execution frame.
2.The execution frame determinesthe control flow after the
execution of the code block completes.
3. It definesnamespacesfor the code block
• Namespace: Anamespace is like adictionary. You can consider the
names(identifiers/variable names) askeysof this dictionary and
the correspondingvaluesto be the objectsto which they point to.
42. Regular Expressions
• Regular expressionsare avery powerful tool in any language. They
allow patternsto be matched against strings.
• Regular expressionsin Python are handled by usingmodule ‘re’.
• Import re
test ='This is for testingregular expressionsin Python.‘
• result =re.search('(Th)(is)',test)
print result.group(0), result.group(1)
• result =re.match(‘regular’, test)
print result – None (match only at the beginningof string)
• ourPattern =re.compile ( '(.*?)(the)' )
testString='This is the dogand the cat.‘
result =ourPattern.match ( testString )
result.group ( 0 )
43. • Regular expressionsuse the backslash character ('') to indicate
special formsor to allow special charactersto be used without
invokingtheir special meaning.
• What if we want to use ‘’ in file path?
• The solution isto use Python’sraw stringnotation for regular
expression patterns; backslashesare not handled in any
special way in astringliteral prefixed with 'r'.
• f =open(r"c:Windowsnotepad.exe", "r")
• Special characters: ‘.’, ‘^’, ‘$’,’*’,’+’,’?’,{m}, {m,n},’’, ‘| ’, ‘(…)’, ‘d’, ‘D’,
‘s’, ‘S’, ‘w’, ‘W’
• re.split('[a-f]+', '0a3B9’) - ['0', '3', '9']
44. • someString='I have adream.'
print re.sub ( 'dream', 'dog', someString)
print someString
• Regular Expressionsdon’t change the actual string.
• Regular Expressionsare very helpful but resource intensive. It
should not be used for matchingor findingsimple texts.
45. Some Concepts…
• An execution frame createstwo kindsof namespacesfor acode
block, namely local and global. The third type of namespace is
called the built-in namespace and is created when the Python
interpreter loads.
• bindingand unbinding:
1.When you define afunction, you bind the formal parameters.
2.You bind aname when you use an import construct (to the
namespace of the block which containsthe import statement).
3.When you define a class or a function, using the class and def
keywords, you bind the names of the functions and classes and
they are available in the containingblock (e.g. amodule)
4. When you do an assignment operation
5.The loop control variable in afor loop construct createsa
dynamic binding
6. In an except clause, when you provide argument to the clause
46. Modules
• How do I use an existingmodule and the functionsand classes
contained in it?
To use an existingmodule, you need to first create areference to it
in the current namespace. In simple words, you would need to
import amodule to use itsfunctionality.
• How do I know whether amodule is available in current
namespace?
You can use dir() built in command to check what all reference
variablesare available to you in current namespace. You can go one
step ahead and use dir() to see what referencesare available in a
particular object's(e.g. module's) namespace by passingobject as
the argument.
• import random
dir(random)
47. Modules…
• ImportingModules:
import random
from random import randint
from random import *
import random asRand
• Accessclassesand functionsof module:
For thismodule name and the dot operator should be used.
• Importingmodulesin blocks?
• From <modulename>import <functionanme>
48. OOPin Python
• Python asalanguage is built in object oriented way. Everythingis an
object in Python and it really meansso.
• When compared with other Object Oriented languageslike C++ and
Java, you will observe that most of the featuresare available in
Python, in amuch simpler way. You will also observe that many of
the accessrelated features(and those loadsof keywordsand rules)
are not there.
• Inheritance
• Multiple inheritance
• Abstraction
• Polymorphism
• Overriding
• Operator Overloading
• Object Instances
49. Classesin Python
• Creatingaclass:
classMyClass:
pass
• Instantiatingaclass:
a=MyClass()
print a
< main .MyClassinstance at 0x01206A08>
Yes, it does look like a function call, in fact you can very well have a
function and a class with the same name in your Python code. The
syntax for instantiation and function call will look exactly the same.
Python understandsthe type of any variable based on the object to
which it points. So, if MyCode pointsto the body of aclass, it a =
MyCode() instantiatesaclassand if it pointsto afunction body, the
function is called and aholdsitsreturn values.
50. Amore meaningful Class
• classSimpleClass:
def init (myVal):
self.myVal =myVal
def getValue(self):
return self.myVal
def setValue(self, newVal):
self.myVal =new Val
• The classSimpleClasshasthree methodsinside it.
• The first one hasthe name _ _init_ _ and iscalled the
constructor. The name of thismethod should alwaysbe _init_
_. It takesthe argument myVal. Thisvalue isused to initialize
an object. Thismethod isused frequently to initialize an
object with agiven state, rather than calling a whole set of
functionsto set itsstateafter creation.
51. • self is aconvention used by Python programmers to depict the
current object reference. Unlike many other OOPlanguages, the
current object reference hasto be explicitly defined in Python class
definitions- instance variablesand methods. The first argument of
every method hasto be self. This argument is used only while
definingthe method, in the method call, it is omitted.
• Inside the _ _init_ _, it saysself.myVal =myVal. This is asimple
assignment operation. Here self.myVal definesan instance variable
(object variable).
• We see two other methods, which look like normal functions. The
difference beingthat they are bound to an object and there is
essentially alot of information which need not be passed to them
asargumentsevery time, asthey have accessto the object
variablesand classvariables(we'll discussabout classvariables
later).
52. • getValue() returnsthe value of the self.myVal and setValue() setsit
to the value that is passed.
• get and set functionsare called accessorsand mutators
respectively. They have alot of utility in preventingthe private
variablesof aclassfrom gettingmodified inaccurately or
unexpectedly.
• simpleClassObject =SimpleClass(12) print "Value: " +
str(simpleClassObject.getValue()) simpleClassObject.setValue(15)
print "Value: " +str(simpleClassObject.getValue())
• Value: 12
Value: 15
53. classA:
def init (self):
print "Called A"
def local(self):
print "In local"
def load(self):
print "Loaded from A"
self. local()
classB():
def init (self):
print "Called B"
def load(self):
print "Loaded from B“
classC(B,A):
def init (self):
a=A()
print "In C“
c=C()
c.load()
if hasattr(C, "load"):
print "yes"
54. Staticanalysisof code
• PyChecker is astatic analysistool that findsbugsin Python source
code and warnsabout code complexity and style.
• Pylint is another tool that checksif a module satisfiesa coding
standard, and also makes it possible to write plug-ins to add a
custom feature.
• Pylint more popularly used.
55. Exception Handling
• The statementsused to deal with exceptionsare raise and except.
• def throws():
raiseRuntimeError('this is the error message')
def main():
throws()
if name ==' main ':
main()
• Traceback (most recent call last): File "throwing.py", line 10, in
<module> main()
File "throwing.py", line 7, in main throws()
File "throwing.py", line 4, in throwsraise RuntimeError('this isthe
error message')
RuntimeError: this is the error message
56. • f =None
try:
f =open("aFileName")
f.write(could_make_error())
except IOError:
print "Unable to open file"
except: # catch all exceptions
print "Unexpected error"
else: # executed if no exceptionsare raised
print "File write completed successfully"
finally: # clean-up actions, alwaysexecuted
if f:
f.close()
• Raise – re-raisesthe same exception thrown and dies.
57. Garbage Collection
• Python'smemory allocation and de-allocation method is automatic.
• Python usestwo strategiesfor memory allocation reference
countingand garbage collection.
• Reference countingworksby countingthe number of timesan
object isreferenced by other objectsin the system. When
referencesto an object are removed, the reference count for
an object isdecremented. When the reference count
becomeszero the object isde-allocated.
• Caveat isthat it cannot handle referencecycles.
• def make_cycle():
l =[ ]
l.append(l)
58. • Garbage collection is ascheduled activity. Python schedulesgarbage
collection based upon athreshold of object allocationsand object
de-allocations.
• import gc
print gc.get_threshold()
(700,10,10) - This meanswhen the number of allocationsvs. the
number of de-allocationsis greater than 700 the automatic garbage
collector will run.
• The garbage collection can be invoked manually in the
following way:
import gc
gc.collect()
• gc.collect() returnsthe number of objectsit hascollected and
deallocated.
59. Logging
• Loggingis performed by callingmethodson instancesof
the Logger class.
• The methodsare debug(), info(), warning(), error() and critical(),
which mirror the default levels.
• import logging
LOG_FILENAME='example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.D
EBUG)
logging.debug('Thismessage should go to the logfile')
• File Contents:
DEBUG:root:Thismessage should go to the logfile.
• Messageswith higher precedence get logged to the
LOG_FILENAME.
60. Python in Astronomy
• pFitsio or PyFitsand the NumPy, SciPy, astronomical imagesand
tablescan be easily accessed and manipulated asnumerical arrays.
• BoA(Bolometer Analysis Package)
• Astro-WISE(widefield imagingsystem)
• astLib – Python Astronomy Modules- astronomical plots, some
statistics, common calculations, coordinate conversions, and
manipulatingFITSimageswith World Coordinate System
(WCS) information through PyWCSTools