nano_exit

基礎的なことこそ、簡単な例が必要だと思うのです。

外部プログラムをpythonでループさせて動かす(自分用のメモ)。

pythonを使って外部プログラムをループ動作させる。

エラーが起こることを想定して、適当にエラーを起こさせるためのfortranプログラムのソースを用意。

! test.f90
program test
open( 10, file = 'test.inp', status = 'old' )
end program test

適当にコンパイルしておく。

gfortran test.f90 -o test.out

ループの途中でのファイルのやり取りを想定して、適当なテキストファイルを用意。

touch a.txt

適当なループでtest.outを繰り返し動作させるpythonスクリプト
errorを発生させるため、test.outが読み込むtest.inpを用意せずに動かす。
発生したerrorはtest.errに書き込ませるため、動作は途中で止まらず、故にループも止まらない。
以下のスクリプトでは、各ループでの結果を別々のディレクトリに保存することを想定しているため、ディレクトリ及びパス操作が含まれている。

# test.py

import os
import shutil
import time
from subprocess import call

time_start = time.time()

# corrent work directory
cwd = os.getcwd()

# arbitrary loop
for i in range(3):

    # directory path which stores results
    path = './test{}'.format( i )

    # check path and make directory
    if os.path.exists( path ):
        print( '{}.exists.'.format( path ) )
    else:
        os.makedirs( path )

    # copy required files from cwd
    shutils.copy( cwd + '/a.txt', path + '/a.txt' )

    # change directory
    os.chdir( path )
    
    # main operation
    cmd = '{}/test.out 2> test.err'.format( cwd )
    call( cmd. shell = True )

    # return to the original directory
    os.chdir( cwd )

time_end = time.time()
dt = time_end - time_start
print( 'time: {:.1f}'.format( dt ) )
print( 'time: {:d}h {:d}m'.format( int(dt/3600), int(dt%3600/60) )