<p>如果您的Fortran程序(即<code>'./output.e'</code>AFAICS)可以从<code>stdin</code>读取,而不仅仅是从常规文件读取,那么您可以通过传递它<code>stdin=subprocess.PIPE</code>(<a href="https://docs.python.org/2/library/subprocess.html?highlight=popen#frequently-used-arguments" rel="nofollow">other valid values are</a><em>“一个现有的文件描述符(一个正整数)[或]一个现有的文件对象”</em>)而不需要临时文件。在UNIX中,总是有<code>/dev/stdin</code>放在命令行上,而在Windows中,总是有<code>con</code>。你知道吗</p>
<p>不过,如果由于处理的性质,程序只能在“会话”中工作(即不能连续运行并在可用时提供新数据),则必须重复调用它。你知道吗</p>
<p>请注意,您必须在不同的线程中处理不同的管道,以避免死锁。因此,要么使用<a href="https://docs.python.org/2/library/subprocess.html?highlight=popen#subprocess.Popen.communicate" rel="nofollow">^{<cd6>}</a>(但是程序不能连续运行),要么手动生成一个<code>stdout</code>/<code>stderr</code>线程(这就是<code>communicate()</code>所做的;不要<code>stdin</code>,因为输出读取代码必须在开始写入<code>stdin</code>时运行,否则外部程序在写入时可能会因“设备上没有空间”而阻塞)。你知道吗</p>
<p>下面是连续运行程序的示例代码:</p>
<pre><code>p=subprocess.Popen(argv,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
while True:
#the only more elegant way to return a value from a thread is with a Thread subclass,
# see http://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python
output_container=[]
ot=threading.Thread(target=_outputreaderthread,args=(p.stdout,output_container,data))
ot.start()
p.stdin.write(data)
ot.join()
output=output_container[0]
data=process_output(output)
if no_more_processing_needed(data): break
p.stdin.close()
if p.wait()!=0:raise subprocess.CalledProcessError(p.returncode,argv)
def _outputreaderthread(stream,container,data):
#since there's no process termination as an end mark here,
# you need to read exactly the right number of bytes to avoid getting blocked.
#use whatever technique is appropriate for your data (e.g. readline()'s)
output=stream.read(calculate_output_size(data))
container.append(output)
</code></pre>