2016-06-25 2 views
1

파이썬 코드에서 FreeFem ++로 작성된 함수를 호출 한 다음 FreeFem ++ 코드의 출력을 텍스트 파일에 저장하고 파이썬에서 읽고 싶습니다. .파이썬의 다른 함수로 작성하기 전에 텍스트 파일을 읽는 방법

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가 생성되지 않았기 때문에, 그것은 out.txt가 존재하지 않는 말을 나에게 오류를 제공한다는 것입니다!

+1

'os.system'은 다소 조잡합니다. [subprocess] (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 

마지막으로, 가장 우아한 해결책이 될 것 ++ 프로그램은 모든 것을 stdout에 출력하고, 그 출력을 파이썬 내에서 파이프를 통해 가져온다. 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 파일을 저장할 때 잘 작동합니다. 내 변수의 문자열을 사용하여 내 파일을 저장하면 오류가 발생합니다. myfile = open ("Data _"+ 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'를 사용하여 파일 존재 여부를 확인하기까지 그것을 인쇄 할 수 있습니다 .O 또한 컨텍스트 관리자를 사용하여 파일을 엽니 다 (' open (...) as f') 파일 누설을 피하십시오. – zmo

+0

현대적인 파이썬에서는 더 이상 사용되지 않는'os.system()'이 아니라'subprocess'를 사용하십시오. – zmo

관련 문제