2016-06-25 8 views
1

に別の関数によって作成される前に、テキストファイルを読み込む方法を、私はFreeFemで書かれた関数を呼び出し++、その後、私は、テキストファイルにFreeFem ++コードからの出力を保存し、私はPythonでこれを読みたいです。私のpythonコードでのpython

def f(x): 
    os.system("Here the FreeFem++ code will be called and the result will be saved as out.txt") 
    myfile=open("out.txt") 
    return myfile.read() 

問題は、out.txtをが作成されていないとして、私は、Pythonのコードを実行すると、それはout.txtを存在しないと言って私にエラーを与える、ということです!

+1

'os.system'はかなり粗雑です。 [サブプロセス](https://docs.python.org/3/library/subprocess.html#module-subprocess)それは学習曲線のビットを持っているが、あなたはより多くの制御を_far_できます。 –

+1

ファイルがスクリプトと同じフォルダに保存されていますか? – zondo

+0

あなたのお返事ありがとうございます。実際に私のテキストファイルは次の形式になっています(パラメータが無ければ正常です) – Mohammad

答えて

4

使用subprocess.run()あなたfreefem ++プログラムを呼び出し、それが存在する前に、あなたの呼び出しは、実際にファイルを生成していることを確認します。 openの直前にブレークポイントを追加することで確認できます。

ので、サブプロセスに変更します。

def f(x): 
    cp = subprocess.run(['freefem++', '--argument', '--other_argument']) 
    if cp.returncode != 0: 
     print('Oops… failure running freefem++!') 
     sys.exit(cp.returncode) # actually you should be raising an exception as you're in a function 
    if not os.path.exists('out.txt'): 
     print('Oops… freefem++ failed to create the file!') 
     sys.exit(1) # same you'd better be raising an exception as you're in a function 
    with open('out.txt', 'r') as ff_out: 
     return ff_out # it is better to return the file object so you can iterate over it 

ファイルが実際にそれを開く前に作成されていることを確認するには:あなたはfreefemことを確認するために

def f(x): 
    cp = subprocess.run(['freefem++', '--argument', '--other_argument']) 
    if cp.returncode != 0: 
     print('Oops… failure running freefem++!') 
     sys.exit(cp.returncode) 

    # XXX Here we make a breakpoint, when it's stopping open a shell and check for the file! 
    # if you do not find the file at this point, then your freefem++ call is buggy and your issue is not in the python code, but in the freefem++ code. 
    import pdb;pdb.set_trace() 

    with open('out.txt', 'r') as ff_out: 
     return ff_out # it is better to return the file object so you can iterate over it 

最後に、最もエレガントな解決策は次のようになり++プログラムはすべてを標準出力に出力し、その出力をPython内のパイプを通して、subprocess.popen()

def f(x): 
    p = subprocess.popen(['freefem++'…], stdout=subprocess.PIPE) 
    out, _ = p.communicate() 
    if p.returncode != 0: 
     raise Exception('Oops, freefem++ failed!') 
    return out 
+0

で同じ形式のテキストファイルを保存しているが、私に、ご説明いただき、誠にありがとうございます以前の呼び出しの方法は、単純なname.txtでtxtファイルを保存するとうまくいきます。問題は、ファイルを保存するために変数の文字列を使用し、エラーが発生することです。私は、この形式で私のtxtファイルを読みたい:myfileを=オープン( "データ_" + STR(X [0,0]/3600)+ "_" + STR(X [0,1])+ "_" + STR (x [0,2])+ "。txt") – Mohammad

+0

ファイル名の生成( 'data _ {} {}。txt" .format(x、y、z) ')をよりよく制御するために、それを変数として設定してから、あなたが正しいことを確認し、 'os.path.exists'を使ってファイルの有無をチェックすることさえできます。ああ、コンテキストマネージャを使ってファイルを開きます(' )F'として(...)オープンでファイルディスクリプタを漏洩しないようにする。 – zmo

+0

そして、それが現代のpythonで非推奨と考えられているとして、 'subprocess'なく' os.systemを() 'を使用します。 – zmo