在我的python代码中,我调用了一个用FreeFem++编写的函数,然后将FreeFem++代码的输出保存在一个文本文件中,我想在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()问题是,当我运行python代码时,由于还没有创建out.txt,它会给我一个错误,告诉我out.txt不存在!
发布于 2016-06-25 19:09:29
使用subprocess.run()调用您的freefem++程序,并确保您的调用在文件存在之前实际生成了该文件。您可以通过在open之前添加断点来检查这一点。
因此,更改为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要在打开文件之前检查文件是否已创建,请执行以下操作:
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中的管道获取输出
def f(x):
p = subprocess.popen(['freefem++'…], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode != 0:
raise Exception('Oops, freefem++ failed!')
return outhttps://stackoverflow.com/questions/38027726
复制相似问题