[Tutor] re-directing print statements in exec
Jeff Shannon
jeff at ccvcorp.com
Thu Oct 9 21:00:31 EDT 2003
Toby Donaldson wrote:
> Hi all,
>
> I am wondering if there is any easy way to make a print statement in an
> exec statement get sent to a string instead of the console. For instance,
>
>>>> prog = """
> r = 5
> print 3.14 * r ** 2
> """
>>>> exec prog
> 78.5
>
> The result gets printed to the console. But instead, I'd like it to be
> in a string.
>
> Any suggestions?
First off, I'd suggest just using a function instead of exec. ;)
def prog():
r = 5
return 3.14 * r**2
result = prog()
Of course, it'd probably be better to pass r in as a parameter, and to
rename the function so that it's meaningful...
def circle_area(r):
return 3.14 * (r**2)
result = circle_area(5)
There are *very* few situations in which exec is truly the most
desirable tool, and many situations in which it creates programs that
are actively dangerous. The use of exec and its cousin eval() should
always be considered to be deep black magic -- it is not suitable (nor
intended for) everyday use. Unless you're writing an interactive
shell replacement or a code debugger or some such, I *strongly*
recommend against using exec.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list