Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read and execute the scripts in file

Tags:

python

This is a simplified example, the python program run on a device and wait for a text file to understand how to execute the next step, the text file will be upload to the device frequently.

How to let the python program "translate" the text file (in this example, steps.txt only has one line "z = x + y") into the executable script?

import os
import time
x = 3
y = 9
s = None
while 1:
  time.sleep(1)
  try:
    with open("steps.txt", 'r') as f:
        s = f.readline()#s = "z = x + y"
        f.close()
        break
except:
    pass

os.system(s)#'z' is not recognized as an internal or external command,operable program or batch file.
like image 915
adameye2020 Avatar asked Mar 17 '26 16:03

adameye2020


2 Answers

As you included in your post, the command prompt returned this error

'z' is not recognized as an internal or external command,operable program or batch file.

when you passed the string "z = x + y" into os.system(). That is because the command is not run in python. I believe what you were trying to do was

# s = "z = x + y"
os.system(f'python -c "{s}"')

which would of course return a NameError.

Instead, to execute the line of code in your python program, use the exec() method, like so:

# s = "z = x + y"
exec(s)

But be warned! Both exec() and eval() should really be avoided, as they pose serious security issues.

Note: The f.close() isn't necessary as you used the with statement.

like image 75
Ann Zen Avatar answered Mar 20 '26 07:03

Ann Zen


Instead of os.system(s), you could use exec:

exec(s)

But note that this is really unsafe, more details here.

like image 41
U12-Forward Avatar answered Mar 20 '26 06:03

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!