[Tutor] getting input for stdin

Alan Gauld alan.gauld at btinternet.com
Mon Dec 8 09:53:02 CET 2014


> On 08/12/14 03:50, diliup gabadamudalige wrote:
>> I managed to get the output file and input file working.
>> The output works fine but the input does not. It simply exits the
>> program. No crash. Exits.It DOES NOT WAIT FOR ME TO TYPE IN THE
>> inputfile.txt

Can you show us what your input file looks like?

>> if __name__ == '__main__':
>>     ## menna me kaalla to change the output path
>>     p = os.getcwd()
>>     outfile = "\output_file.txt"
>>     infile = "\input_file.txt"

One point, you probably should make these raw strings otherwise the 
first character may get interpreted as a specioal one due to the back slash:

    infile = r"\input_file.txt"

I assume you are running on Windows?
And you use the \ as a path specifier?

>>     outfilepath = p + outfile
>>     infilepath = p + infile

You should use os.path.join to do this safely and portably.

>>     sys.stdout = open(outfilepath, "w+")
>>     sys.stdin = open(infilepath, "w+")

You probably should make the input have read mode.
Using 'w+' for an input is not usually what you want.

>>     os.startfile(outfilepath)
>>     os.startfile(infilepath)

What do you think this does? I suspect it starts a
copy of Notepad running? Is that right? Any changes in the files
will not be reflected in Notepad, and any changes in Notepad
will not be reflected in the files until the user saves the file.

However you may also have problems opening the files since the
OS should have put a lock on them when Python opened them in
write mode.

>>     run = True
>>     while run:
>>         scaletemplate = ["C", "D", "E", "F", "G", "A", "B"]
>>         getscale = sys.stdin.readline()
>>         raw_input("Which scale do you require?:")

I suspect the prompt will get printed on the console (using stderr)
but you are not assigning the return value (from infile.txt) to anything 
so it will get lost.

I suspect you want to reverse those lines and use a print:

       print "Which scale do you require?:"
       getscale = sys.stdin.readline()

>>         if len(getscale) > 1:
>>             getscale = getscale[0].upper() + getscale[1:]

Don't you only want the first character? Otherwise it might mess up the 
'in' test below. If not, you could use string.capitalize() to do it in a 
single operation.

>>         else:
>>             getscale = getscale.upper()

>>         if getscale in data.scalenames:
>>             scale = main(getscale)

Where did main() come from? It's not defined in your code?

>>             print scale
>>
>>         elif getscale == "Q" or getscale == "X" or getscale == "":
>>             run = False
>>             print"exiting..."

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list