W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
You want a script you’ve written to be able to accept input using whatever mechanismis easiest for the user. This should include piping output from a command to the script,redirecting a file into the script, or just passing a filename, or list of filenames, to thescript on the command line.
Python’s built-in fileinput module makes this very simple and concise. If you have ascript that looks like this:#!/usr/bin/env python3import fileinput
with fileinput.input() as f_input:for line in f_input:print(line, end='‘)
Then you can already accept input to the script in all of the previously mentioned ways.If you save this script as filein.py and make it executable, you can do all of the followingand get the expected output:
$ 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.
The fileinput.input() function creates and returns an instance of the FileInputclass. In addition to containing a few handy helper methods, the instance can also beused as a context manager. So, to put all of this together, if we wrote a script that expectedto be printing output from several files at once, we might have it include the filenameand line number in the output, like this:
>>> import fileinput
>>> with fileinput.input('/etc/passwd') as f:
>>> for line in f:
... print(f.filename(), f.lineno(), line, end='')
...
/etc/passwd 1 ##
/etc/passwd 2 # User Database
/etc/passwd 3 #
Using it as a context manager ensures that the file is closed when it’s no longer beingused, and we leveraged a few handy FileInput helper methods here to get some extrainformation in the output. Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: