Posts

Showing posts from August, 2024

Running python code from file using exec()

Image
The exec function in python can be used to execute strings as python code. One of the simplest example can be as follows: a=2 exec("print(a)") 2 Note that we have not directly used the print() function to print the value of variable a , but have given the code print(a) as a string input to the exec function. The ability to excute strings as python code can be used to excute code stored in text files. A larger software tool can generrate a code in terms of variable that can be used in later steps of the program. It can also, be used to perfrom repetative tasks. Let’s say we have to run some imports statements and some code everytime you start a new session of python. We want those imported packages and variables available on the workspace console instead of inside a module. In this case you can just make a file that contains all those commands and run those commands via exec . We will see an example here. Let’s say we want to import matplotlib, numpy, pandas, s...