首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中的另一个函数创建文本文件之前读取该文件

如何在python中的另一个函数创建文本文件之前读取该文件
EN

Stack Overflow用户
提问于 2016-06-25 18:58:22
回答 1查看 145关注 0票数 1

在我的python代码中,我调用了一个用FreeFem++编写的函数,然后将FreeFem++代码的输出保存在一个文本文件中,我想在python中读取它。

代码语言:javascript
复制
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()

问题是,当我运行python代码时,由于还没有创建out.txt,它会给我一个错误,告诉我out.txt不存在!

EN

回答 1

Stack Overflow用户

发布于 2016-06-25 19:09:29

使用subprocess.run()调用您的freefem++程序,并确保您的调用在文件存在之前实际生成了该文件。您可以通过在open之前添加断点来检查这一点。

因此,更改为subprocess:

代码语言:javascript
复制
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

要在打开文件之前检查文件是否已创建,请执行以下操作:

代码语言:javascript
复制
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

最后,对于您来说,最好的解决方案是让freefem++程序将所有内容输出到标准输出,然后使用subprocess.popen()通过python中的管道获取输出

代码语言:javascript
复制
def f(x):
    p = subprocess.popen(['freefem++'…], stdout=subprocess.PIPE)
    out, _ = p.communicate()
    if p.returncode != 0:
        raise Exception('Oops, freefem++ failed!')
    return out
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38027726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档