[Tutor] A question about using stdin/out/err vs named files
Peter Otten
__peter__ at web.de
Sun Oct 19 10:05:15 CEST 2014
George R Goffe wrote:
> When you run a python program, it appears that stdin, stdout, and stderr
> are opened automatically.
>
> I've been trying to find out how you tell if there's data in stdin (like
> when you pipe data to a python program) rather than in a named input file.
> It seems like most/all the Unix/Linux commands are able to figure this
> out. Do you know how Python programs do this or might do this?
I don't think there is a way to guess that. Instead there is an optional
commandline argument; if that is missing or '-' the script assumes stdin as
the default. With argparse you spell it like this:
$ cat upper.py
#!/usr/bin/env python3
import argparse
import sys
parser = argparse.ArgumentParser(description="Convert input to uppercase")
parser.add_argument(
"input", type=argparse.FileType("r"), default=sys.stdin, nargs="?",
help="Input file or '-' for stdin. Default: stdin.")
for line in parser.parse_args().input:
print(line.upper(), end="")
$ ./upper.py
Hello
HELLO
$ ./upper.py upper.py
#!/USR/BIN/ENV PYTHON3
IMPORT ARGPARSE
IMPORT SYS
PARSER = ARGPARSE.ARGUMENTPARSER(DESCRIPTION="CONVERT INPUT TO STDIN")
PARSER.ADD_ARGUMENT(
"INPUT", TYPE=ARGPARSE.FILETYPE("R"), DEFAULT=SYS.STDIN, NARGS="?",
HELP="INPUT FILE OR '-' FOR STDIN. DEFAULT: STDIN.")
FOR LINE IN PARSER.PARSE_ARGS().INPUT:
PRINT(LINE.UPPER(), END="")
There is also the fileinput module.
More information about the Tutor
mailing list