Reputation: 59
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.
Upvotes: 3
Views: 489
Reputation: 27577
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.
Upvotes: 4
Reputation: 71610
Instead of os.system(s)
, you could use exec
:
exec(s)
But note that this is really unsafe, more details here.
Upvotes: 2