Mohammad
Mohammad

Reputation: 57

how to read a text file before being created by another function in python

In my python code, I call a function written in FreeFem++ and then I save the output from FreeFem++ code in a text file and I want to read this in 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()

The problem is that, when I run the python code, as the out.txt has not been created, it gives me an error saying the out.txt doesn't exist!

Upvotes: 1

Views: 242

Answers (1)

zmo
zmo

Reputation: 24812

Use subprocess.run() to call your freefem++ program, and make sure that your call actually generates the file before it exists. You could check that by adding a breakpoint just before the open.

So change to subprocess:

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

To check that your file is indeed created before opening it:

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

Finally, the most elegant solution would be for you to make that the freefem++ program outputs everything to stdout, and that you take that output through a pipe within python, using 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

Upvotes: 4

Related Questions