Skip to main content

eval,exec, execfile, compile and py_compile in python

Importance of eval, exec, execfile, compile; and the py_compile module:


eval(str,globals,locals)
This function executes an expression string and returns the result.

>>> eval('2+3')
5
>>> eval("'udhay'*3")
'udhayudhayudhay'


#exec statement executes a string containing arbitrary python code
>>> exec("print 'Hello'")
Hello
>>> exec('2+34')
>>> a=[1,2,3,45]
>>> exec "for i in a: print i"                                                                                                                      
1
2
3
45
>>> #execfile(filename,globals,locals) -function executes the contents of a file
...
>>> execfile("fileName.py")

In [1]: globals={'x':7,'y':10,'birds':['parrot','pigeon','sparrow']}

In [2]: locals={}                                                                                                                                    

In [3]: a=eval("3*x+4*y",globals,locals)

In [4]: a                                                                                                                                            
Out[4]: 61

In [5]: exec "for b in birds: print b" in globals,locals
parrot
pigeon
sparrow

execfile("fileName.py",globals,locals)

# when a string is passed to exec,eval(), or execfile(), parser first compiles to create bytecode.

# To remove this redundant process every time, compile will create precompiled bytecode,
# which can be used everytime, till the code is not changed

#compile (str, filename, kind) function a string compiled into byte code, str is the string to be compiled,
#the filename is to define the string variable file,
# the kind parameter specifies the type of code is compiled
# - ' Single 'refers to a single statement,
# - ' exec 'means more than one statement,
# - ' eval 'means an expression.

#compile () function returns a code object, the object, of course, can also be passed to the eval () function
#and the exec statement to perform, for example, :

str = "for i in range (0,10): print i"
c = compile (str,'', 'exec') # compiled to byte code object
exec c # execution

str2 = "3 * x + 4 * y"
c2 = compile (str2,'', 'eval') # compiled expression

py_compile - It is a module to create bytecode file, .pyc
In [14]: import py_compile

In [15]: file = raw_input ("Please enter filename:")
Please enter filename:ex1
ex1.py       ex1.py.save  ex1.pyc  
Please enter filename:ex1.py

In [16]: py_compile.compile (file);            

In [17]: ls *.pyc                                                                                                                                    
ex1.pyc


*****
In Python 2.x input(...) is equivalent to eval(raw_input(...)), in Python 3.x raw_input was renamed input
>>>a=input
>>> a=input()
udha
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'udha' is not defined
>>> udha
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'udha' is not defined
>>> a=input()
'jbasdf'
>>> a=raw_input()
aFDF

Comments

Popular posts from this blog

NSG 2.1 Tcl/OTcl Script Generator

Are you a beginner for ns2 network simulator? Are you afraid of Tcl/oTcl script generation? Then there is a tcl script generator, named NSG 2.1 NSG - Network Simulation Generator NSG 2.1 is a java .jar file.  So, this application can run on all platforms (windows/linux/mac os). It deserves the java installed in you pc, prior to working with NSG 2.1. Java must be installed to run NSG2.1. So, initially, java must be installed. How to install java in Windows/ubuntu/mint/debian linux/ OS X ? Step 1 : Go to Terminal and run  java -version   to check the java version installed in your machine. Step 2 :  For Windows, click here  to download the java installer. Then, it is a typical next-next windows executable installation. For ubuntu/mint/debian linux operating systems, run the following commands in that terminal: sudo apt-get install default-jre sudo apt-get install default-jdk sudo apt-get install openjdk-7-jre sudo apt-get install...

List of Websites to get free e-books

Here follows the list of websites to download e-books for free. 1. www.bookfi.org 2. www.bookzz.org  These two websites offer 4 to 5 free downloads per day. Best advantage is that we need not go for any sign-in process or clicking on an advertisement. 3. http://manybooks.net      In this website, apart from downloading in pdf format, one can download in many other e-book formats. 4. www.ebookee.org 5. www.bookboon.com 6. www.gutenberg.org 7. www.books123.me   8. www.brupt.com This website provides file in word (.doc), powerpoint (.ppt) and pdf file formats. 9. www.pdfoxy.com This website provides books in pdf format, but we should wait for 12-15 seconds and enter a Captcha code. But no need to sign-in. 10. www.docstoc.com This is another decent website of downloading ebooks in .pdf format, with no advertisement and no signing in. 11. www.freecomputerbooks.com This is one of the best websites for downloading technical and profession...

SUMO installation in linux (Debian/Ubuntu/Mint)

SUMO - S imulation of U rban Mo bility SUMO an open source, portal, microscopic, multi-modal road traffic simulation. It allows for intermodal simulation including pedestrians and comes with a large set of tools for scenario creation.  It allows to simulate as to how a given traffic demand which consists of single vehicles moves through a given road network. The simulator allows to address a large set of traffic management topics. It is purely microscopic: each vehicle is modeled explicitly, has an own route, and moves individually through the network. SUMO Installation Procedure: Installation in Linux and mac OS Step I: Install two pre-requisite packages to build SUMO with GUI. Go to terminal and run: $ sudo apt-get install libgdal1-dev proj libxerces-c2-dev $ sudo apt-get install libfox-1.6-dev libgl1-mesa-dev libglu1-mesa-dev Step II: If you are using Unbuntu 12.04 or older versions, as it doesn't ship with libgdal package, create a symbolic link: $ sudo ln -s /usr/l...