由于这个答案piping data to a python script
在搜索sys
. IMO,即使对新用户来说也更加pythonic和不言自明。
import fileinput
with fileinput.input() as f_input:
for line in f_input:
print(line, end='')
这种方法也适用于如下结构的命令:
$ ls | ./filein.py # Prints a directory listing to stdout.
$ ./filein.py /etc/passwd # Reads /etc/passwd to stdout.
$ ./filein.py < /etc/passwd # Reads /etc/passwd to stdout.
如果您需要更复杂的解决方案,您可以编译argparse
,fileinput
如 martinth 的这个要点所示:
import argpase
import fileinput
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('--dummy', help='dummy argument')
parser.add_argument('files', metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')
args = parser.parse_args()
# If you would call fileinput.input() without files it would try to process all arguments.
# We pass '-' as only file when argparse got no files which will cause fileinput to read from stdin
for line in fileinput.input(files=args.files if len(args.files) > 0 else ('-', )):
print(line)
```