Methods and Functions

Python compile()

In python, if the user has a string of Python code that he wants to compile so that it can be run it later. This is done through the python compile method. It accepts source code as the input, and the output will be a code object that is ready to run.

python compile

Source Code

Here is the syntax of the compile() in the python programing language:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

The code object generated by the compile() method can then be used to execute dynamically generated Python code using methods like exec() and eval().

compile() Parameters

The parameters of the compile() are:

Source- A standard string, a byte string, or an AST object can all be used.

Filename – The code was read from this file. You can give it a name if it wasn’t read from a file.

Mode – The execution mode can be exec, eval, or single.

  1. eval- This is a single expression
  2. exec- It can accept a code block containing Python statements, classes, and functions, etc.
  3. single- If there is only one interactive statement, this mode is used.

Flags- This is an optional parameter by python. It considers how future statements will impact the source’s compilation. The default value is 0.

Optimize- This is an optional parameter by python. It indicates the compiler’s optimization level. -1 is the default value.

Return Value from compile()

To return a python code object, use the compile method.

Example: How does compile() works?

In Python, the compile() method takes in source code and returns a code object that can be run later with the exec() function.

Source Code 1:

                    

#This program demonstrates the working of the compile()

codeInString1 = 'x = 5\ny=6\nsum=x+y\nprint("sum =",sum)'



codeObj1 = compile(codeInString1, 'sumstring', 'exec')



exec(codeObj1)



Output

sum = 11

Example 2:

Program to print the product of two numbers using the compile() in python

Source Code:

                    

sourceCode = 'a = 10\nb = 20\nmul = a * b\nprint("mul =", mul)'
  

# Creating an executable from the above source code

exeCode1 = compile(sourceCode, 'mulstring', 'exec')

  

# Running the executable code.

exec(exeCode1)



Output:

mul = 200



Example 3:



b = 50

# For single statements, eval is utilised.

z = compile('b', 'test', 'single')

exec(z)



Output:

50

Can Python Compile?

A python program is compiled before being interpreted. Many programmers believe it is an interpreted language because the compilation part is hidden from them. When we execute our code, it generates byte code, which is then transformed by the python virtual machine(p.v.m) according to the underlying platform.

How do you Compile in Python?

In python, we can use the compile() to compile the given code. If you want to convert Python code from a string or an AST object to a code object, you can use the compile() method.

The code object produced by the compile() method can then be used to execute dynamically generated Python code using methods like exec() and eval().

Example to demonstrate how to read a file’s code and compile it

Let’s say we have mycode1.py file with the following content.

                    

q = 10  

r = 20  

print('Multiplication = ', q* r)  



We can read the contents of this file as a string, compile it into a code object, and run it.



# reading the file's code  

f1 = open('my_code.py', 'r')  

code_str1 = f1.read()  

f1.close()  

code = compile(code_str1, 'mycode1.py', 'exec')  

exec(code)  



Output:

Multiplication =200

Can you compile Python into EXE?

code for making an exe file for python:

pip install pyinstaller

cd PathOfFile

pyinstaller –onefile -w ScriptName.py

python to exe

pip install pyinstaller

cd FullPathOfFile in cmd console

pyinstaller –onefile pythonScriptName.py

how to run a .exe through python

import os

os.startfile(“C:\Documents and Settings\flow_model\flow.exe”)

Python program on how to compile to the exe file

pip install pyinstaller 

pyinstaller –onefile <your_script_name>.py 

create the exe from python script

pyinstaller –onefile pythonScriptName.py

Does compiled Python run faster?

While a compiled script has a faster startup time (because to the lack of compilation), it does not run faster. When a program is read from a ‘.pyc’ or ‘.pyo’ file, it runs at the same speed as when it is read from a ‘.py’ file; the only difference is the speed with which ‘.pyc’ or ‘.pyo’ files are loaded.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.