1、 The contents of a single file can be used as standard input
create file std.py
import sys
for line in sys. stdin:
print( line, end = "")
stay linux Run under cat /etc/passwd | python std.py
perhaps python std.py < /etc/passwd
It will /etc/passwd Print out the contents of , Pass in the program sys.stdin obtain
sys.stdin Is a normal file object , In addition to reading from standard input , Nothing special . We can also use sys.stdin Call the method of the file object . Such as calling read The function reads everything in the standard input .
create file std2.py
import sys
print( sys. stdin. read())
function cat /etc/passwd | python std2.py
Read the contents of multiple files as standard input
Use fileinput, You can read multiple files given in the command line arguments in turn . In most cases , We call directly fileinput Modular input Method to read the contents by line . For example, create a file read_file.py
import fileinput
for line in fileinput. input():
print( line, end = "")
stay linux Run under python read_stdin.py /etc/passwd /etc/passwd-, Multiple file contents can be output
because fileinput You can read the contents of multiple files , therefore fileinput Some methods are provided to let us know which file the currently read content belongs to . fileinput The common methods used in this paper are :
1、filename: File name currently being read ;
2、fileno: The descriptor of the file ;
3、filelineno: The line being read is the line number of the current file ;
4、isfirstline: Whether the line being read is the first line of the current file ;
5、isstdin: Reading file or reading content directly from standard input .
The code is as follows :
import fileinput
for line in fileinput. input():
meta = [ fileinput. filename(), fileinput. fileno(), fileinput. filelineno(), fileinput. isfirstline(), fileinput. isstdin()]
print( meta)
print( line, end = "")