compile(): compiles a source code string, a byte string, or an AST object into a code object

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

source: String , byte or AST object
filename: file name
mode: exec for sequnce, eval for sequnce of statement , single for interactive statements

Returns code object for execution by exec() , eval() functions.

Using string object

cb=compile('print("Hello")', '', 'single')
exec(cb)  # Hello 

Reading from file

Our sample.txt file
print('plus2net')
fob=open("D:\sample.txt",'r')
str=fob.read()
fob.close()
cb=compile(str,'sample.txt','single')
exec(cb)
Output
plus2net

Example

str="sum([1,2,3,4])"
cb=compile(str,'','single')
exec(cb)
Output
10

Using AST object

import ast
ast_obj = ast.parse("print('plus2net')")
code = compile(ast_obj, filename="", mode="exec")
exec(code)  # plus2net

All Built in Functions in Python exec() eval()
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer