13.1 通過重定向/管道/文件接受輸入

2018-02-24 15:27 更新

問題

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.
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號