[Tutor] can i run the last saved input again
Steven D'Aprano
steve at pearwood.info
Sat Jul 24 08:21:07 CEST 2010
On Sat, 24 Jul 2010 03:46:15 pm ANKUR AGGARWAL wrote:
[...]
> now i want to ask is there's any way that python remembers the input
> i gave it to last time and it just give me the output when i again
> run python prog.py?????? i mean i dont need to give input again. I
> just need to give input only first time and when i run the prog again
> it will pick up the previous one output
> is it possible???
Of course it is possible, many programs do it. You need to save the
information you want to remember to a file, then later read it from
disk.
Here's a skeleton of the idea:
look for the config file
if it exists:
then read the answer from the file
if it doesn't exist, or you can't read from it:
then ask the question
try to save the answer in the config file
do whatever work you want with the answer
The ConfigParser module will be useful for writing the config file.
Something like this should do the job:
import ConfigParser
ini = ConfigParser.ConfigParser()
if ini.read('mysettings.ini'):
# File exists, so use it.
answer = ini.get('main', 'answer')
else:
# No config file. Get the answer from the user, and try to save it.
answer = raw_input("Answer this question! ")
answer = answer.strip()
ini.add_section('main')
ini.set('main', 'answer', answer)
f = open('mysettings.ini', 'w')
ini.write(f)
f.close()
print "Your answer is", answer
although this needs better error checking, particularly where it tries
to write the config file.
--
Steven D'Aprano
More information about the Tutor
mailing list