Skip to content Skip to sidebar Skip to footer

How To Treat Stdin Like A Text File

I have a program that reads parses a text file and does some analysis on it. I want to modify it so it can take parameters via the command line. Reading from the file when it is de

Solution 1:

When you use I/O redirection (i.e. you have < or | or > or << in the command line), that is handled by the shell even before your program runs. So when Python runs, its standard input is connected to the file or pipe you are redirecting from, and its standard output is connected to the file or pipe you are redirecting to, and the file names are not (directly) visible to Python because you are dealing with already open()ed file handles, not file names. Your argument parser simply returns nothing, because there are no file name arguments.

To correctly cope with this, you should adapt your code to work with file handles directly -- instead of, or in addition to, explicit file names.

For the latter scenario, a common convention is to have a special case for the file name - and when that is passed in, use standard input (or standard output, depending on context) instead of opening a file. (You can still have files named like that by the simple workaround of using a relative path ./- so the name is not exactly a single dash.)

Post a Comment for "How To Treat Stdin Like A Text File"