Reputation: 3
When I do this I receive an error :
content = (open("to_be_intepreted.txt").read())
output = exec(content)
f = open("output.txt", "w")
f.write(output)
f.close()
Is there a way to achieve this? The error I receive is:
Write() argument must be str, not None
Upvotes: 0
Views: 607
Reputation: 43495
You could run exec
with new globals
and locals
dictionaries.
with open("to_be_intepreted.txt") as f:
content = f.read()
loc, glob = {}, {}
exec(content, glob, loc)
The result should then be in one of the dictionaries, unless it has gone out of scope before exec
ended.
Upvotes: 0
Reputation: 753
As @ApproachingDarknessFish points out, exec
executes the code and returns None.
Therefore, it's not possible to save the result of exec
to a file. However, there are two options:
Redirect stdout to the output file.
import sys
import traceback
# save a reference to the stdout
stdout_temp = sys.stdout
with open('to_be_interpreted.txt') as tbi, \
open('output.txt', 'w') as out:
# monkey-patch stdout (bad practice)
sys.stdout = out
try:
# execute code using exec (bad practice)
exec(tbi.read())
# or rename to_be_interpreted.txt's extension to be .py and do
# import to_be_interpreted
except:
# display any errors to the screen
traceback.print_exc(file=stdout_temp)
# flush stdout to write contents to file
sys.stdout.flush()
# reset stdout using reference
sys.stdout = stdout_temp
Monkey-patching a built-in module is a bad idea because it may have unintended consequences. However, you could keep the existing format of your to_be_interpreted
file.
In addition to security issues, consider replacing exec
with import to_be_interpreted
after changing the to_be_interpreted
file's extension. Interpreting the code at runtime using import
would let you know where errors are if any.
Wrap the code to be interpreted inside a context.
After opening the file, print the content directly to the output file.
with open('output.txt', 'w') as fp:
# start to-be-interpreted code
print('string to print to output', file=fp)
# end to-be-interpreted code
The advantage is minimal code needs to change in your current script and the file closes automatically.
The disadvantage is references to stdout in to_be_interpreted.txt
need to be replaced with the file.
Comment if you have any questions,
Clay
Upvotes: 1