<p>如果您可以使用<a href="http://docs.python.org/library/argparse" rel="nofollow noreferrer">^{<cd1>}</a>(即Python 2.7+),则它具有对所需内容的内置支持:直接从<a href="http://docs.python.org/library/argparse#printing-help" rel="nofollow noreferrer">^{<cd1>} doc</a></p>
<blockquote>
<p>The <code>FileType</code> factory creates objects that can be passed to the type argument of <code>ArgumentParser.add_argument()</code>. Arguments that have <code>FileType</code> objects as their type will open command-line arguments […] <code>FileType</code> objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable <code>FileType</code> objects and <code>sys.stdout</code> for writable <code>FileType</code> objects.</p>
</blockquote>
<p>所以我的建议是</p>
<pre><code>import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'),
help="Specifies the input file")
parser.add_argument('output', type=argparse.FileType('w'),
help="Specifies the output file")
args = parser.parse_args(sys.argv[1:])
# Here you can use your files
text = args.file.read()
args.output.write(text)
# … and so on
</code></pre>
<p>那你就可以了</p>
<pre><code>> python spam.py file output
</code></pre>
<p>从<code>file</code>读取并输出到<code>output</code>,或</p>
<pre><code>> echo "Ni!" | python spam.py - output
</code></pre>
<p>读取<code>"Ni!"</code>并输出到<code>output</code>,或</p>
<pre><code>> python spam.py file -
</code></pre>
<p></p>
<p>这很好,因为使用<code>-</code>作为相关流<a href="https://unix.stackexchange.com/a/16364"> is a convention that a lot of programs use</a>。如果要指出它,请将其添加到<code>help</code>字符串中。</p>
<pre><code> parser.add_argument('file', type=argparse.FileType('r'),
help="Specifies the input file, '-' for standard input")
</code></pre>
<p>作为参考,使用信息将是</p>
<pre><code>> python spam.py -h
usage: [-h] file output
positional arguments:
file Specifies the input file, '-' for standard input
output Specifies the output file, '-' for standard output
optional arguments:
-h, --help show this help message and exit
</code></pre>