Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Redirect input or output to or from a file
Index -> Programming, Python -> Python Tutorials
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
DtY




PostPosted: Fri Apr 24, 2009 4:02 pm   Post subject: Redirect input or output to or from a file

This is a simple way to redirect all input/output from/to a file. (This can also be done at the command line, however this method makes sure it always goes there)

In python, input and output are file like object in the sys module, so import that.
>>> import sys
There are three objects in here that we want: sys.stdin, sys.stdout, and sys.stderr (These are equivilent to /dev/stdin, stdout, and stderr on *nix respectively)
stdin is what is read with input() and raw_input(), stdout is what is written to with print, and stderr is where the tracebacks go. (stdin defaults to form the keyboard, stdout and stderr default to the terminal)
Since theses are just file like objects, then can be replaced with another file like object:
>>> sys.stderr = open("errorFile","w")
And now let's try something that should give an error:
>>> dsfljkdf
This will give you no error, but not because no error occurred, but because the error output has been redirected to a file.
If you open errorFile with a text editor, you will see: (Actually, you have to make it write the output first, thsi can be done by closing the terminal, or running sys.stderr.flush() )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dsfljkdf' is not defined


Why this is useful
- Input
You can write a complete program and test it by inputting at the terminal, and when you are done, you can make it read from a file by adding a single line.
- Output
Same as for input, you can finish writing a program, then make it put everything into a log file, instead of having to open a file each time to program runs to make sure all the changes you made have worked as expected
- Error
This is probably the most useful. Chances are the programs you write wont be written for python experts, so telling them to open the command prompt, and do everything through there and have them explain to you what output they get, you can tell tell them to send you an email describing what they were doing when the error occurred, along with the error log file.
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Python -> Python Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: