Skip to main content
 首页 » 编程设计

python之在 python 中获取用于执行使用多个线程的进程的实时输出

2025年05月04日12insus

我想使用 python 执行 Fortran 代码的可执行文件,并打印实时输出。我使用 subprocess.Popen 查看实时输出,如图所示 here .当我执行像“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 获取实时输出以执行使用多线程的此类进程?

请您参考如下方法:

以下可运行代码创建一个子进程并打印每行输出所花费的时间。这证明我们可以在数据到达时输出子进程行。

我不知道为什么 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 ms