Running python code from file using exec()
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, scikitlearn everytime you start a session. We can just
make a text file with these commands and run via exec
.
Typically, we also might want to run some other statements of reading
and manipulating some data to run in this session, so that results of
those are available in current session console. We could just write that
code in the text file. In this example, we write the text file named as
code_file.txt
and run it in console. Below is how it looks
like.
To run this file so that all imports are available in console, do the following:
= open('code_file.txt', 'r')
f = f.read()
code
f.close()
exec(code)
Creating an array.
a=array([1, 2, 3])
Creating a pandas series.
b=
0 1
1 2
2 3
dtype: int64
Let’s see if the imports are available in console. We will produce simple numpy array and pandas dataset.