发布于 2015-08-30 07:50:08 | 157 次阅读 | 评论: 0 | 来源: 网络整理

问题

You want a script you’ve written to be able to accept input using whatever mechanism is 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 the script on the command line.


解决方案

Python’s built-in fileinput module makes this very simple and concise. If you have a script that looks like this: #!/usr/bin/env python3 import 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 following and 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 FileInput class. In addition to containing a few handy helper methods, the instance can also be used as a context manager. So, to put all of this together, if we wrote a script that expected to be printing output from several files at once, we might have it include the filename and 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 #

<other output omitted>

Using it as a context manager ensures that the file is closed when it’s no longer being used, and we leveraged a few handy FileInput helper methods here to get some extra information in the output.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务