我想使用python执行Fortran代码的可执行文件,并打印实时输出。如here所示,我使用subprocess.Popen查看实时输出。当我执行像'du‘这样的命令时,我确实会得到实时输出,但我只有在Fortran的可执行文件运行完成后才会得到输出。
我的python脚本的相关部分是:
import subprocess as s
a=s.Popen('./fortran_with_fft.exe', shell=True, stdout=s.PIPE)
for line in iter(a.stdout.readline, ''):
print line当我从终端运行可执行文件时,它运行时没有任何错误,并产生了预期的输出。在python中运行它时不会发生同样的情况。Fortran代码使用fftw使用多个线程执行fft计算。为此,我使用了16个线程。我的Fortran代码的相关部分是:
nthreads=16
CALL sfftw_init_threads
CALL sfftw_plan_with_nthreads(nthreads)
CALL sfftw_plan_dft_3d(plan,ngrid,ngrid,ngrid,delta,delta,FFTW_BACKWARD,FFTW_estimate)
delta=CMPLX(densitycontr,0.0)
CALL sfftw_execute(plan)我怀疑这个不打印实时输出的问题与可执行文件通过fft使用多线程有关。有没有办法通过python获得实时输出,以便执行这些使用多线程的进程?
发布于 2014-10-10 00:14:39
下面的可运行代码创建一个子流程,并打印每一行输出所需的时间。这证明我们可以在数据到达时输出子进程行。
我不知道为什么Fortran程序不能类似地工作。这无关紧要,程序是否使用线程也无关紧要。
来源
#!/usr/bin/env python
'''
pping2.py -- run subprocess, process output as it arrives
'''
# adapted from http://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line
import subprocess, time
def test_ping():
proc = subprocess.Popen(
'ping -c5 8.8.8.8',
shell=True,
stdout=subprocess.PIPE,
)
start = time.time()
for line in iter(proc.stdout.readline, ''):
print '{:.2f} {}'.format(time.time()-start, line.rstrip())
if __name__=='__main__':
test_ping()输出
0.04 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
0.04 64 bytes from 8.8.8.8: icmp_seq=1 ttl=44 time=37.4 ms
1.04 64 bytes from 8.8.8.8: icmp_seq=2 ttl=44 time=36.1 ms
2.04 64 bytes from 8.8.8.8: icmp_seq=3 ttl=44 time=37.2 ms
3.04 64 bytes from 8.8.8.8: icmp_seq=4 ttl=44 time=36.0 ms
4.04 64 bytes from 8.8.8.8: icmp_seq=5 ttl=44 time=36.2 ms
4.04
4.04 --- 8.8.8.8 ping statistics ---
4.04 5 packets transmitted, 5 received, 0% packet loss, time 4005ms
4.04 rtt min/avg/max/mdev = 36.080/36.629/37.417/0.609 mshttps://stackoverflow.com/questions/26277845
复制相似问题