compile()
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
Take precaution by not allowing un-cleaned code to get executed through exec(). There is a potential danger in allowing codes to get executed without proper check.
« All Built in Functions in Python
exec() eval()
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com