[Tutor] Re: input() : part two

Chris Smith smichr at bigfoot.com
Sun May 1 07:36:41 CEST 2005


> I found a work around for the terminal it appears that the message in
> the input("message")  was being assigned to the next variable making
> Matrix=error=alpha

It's good to see that you got this working.  Just a couple notes:

1) Regarding your comment above, it just *looks* like it was doing an  
assignment because of the "=" that you had for the Matrix and error  
prompt strings. If you had used the prompt "?" instead, the first line  
of the file would have been "???".  One way you could also get around  
this is being interpreted in your program is to print a "#" before  
doing any input:

###
print "#", # note the comma which keeps the output on the same line.
Matrix = input("Matrix=")
error = input("error=")
alpha = input("alpha=")
###

This would produce "# Matrix=error=alpha=" in your redirected output.

2) Also, it is possible to do a "redirect" from the IDE by just opening  
a file and then redirecting output to this file:

#----------------------------------------------------------------------- 
--------------
# normal output
fav_number = input("What is your favorite number?")

# output redirected to file
import sys
file_name = 'myCode.py'
file = open(file_name, 'w')     #careful; this overwrites an already  
existing file
old_stdout = sys.stdout         #let's remember where we *were* sending  
output
sys.stdout = file               #now everything that gets printed will  
go the the file

print "print 'my favorite number is',",fav_number

file.close()                    #close the file
sys.stdout = old_stdout         #restore the output

# normal output again
print "Now open and run",file_name
#----------------------------------------------------------------------- 
--------------
'''--the output--
What is your favorite number?42
Now open and run myCode.py
    --end output--'''

In the file that was created there is a single line that, for this  
case, says

###
print 'my favorite number is', 42
###

If it starts to get tricky keeping track of what is being printed to  
the program, you might want to check out the string interpolation  
module that allows you to substitute in variables from your main script  
just by putting a $ before the variable name in a string (e.g.
this:
	printpl("print 'The favorite number is $fav_number'")
will make (with the input from above):
	print 'The favorite number is 42'

The module and demos are at http://lfw.org/python/Itpl.py

Best regards,
/c



More information about the Tutor mailing list