程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Yyds dry inventory standard input of Python skills

編輯:Python

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 = "")
  • 1.
  • 2.
  • 3.
  • 4.

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())
  • 1.
  • 2.
  • 3.

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 = "")
  • 1.
  • 2.
  • 3.
  • 4.

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 = "")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved