Pyomo - 如何将 model.pprint() 写入文件?

Pyomo - how to write model.pprint() to file?

我想要 "debug" 我的 pyomo 模型。 model.pprint() 方法的输出看起来很有帮助,但它太长了,所以控制台只显示和存储最后几行。我怎样才能看到第一行。以及如何将此输出存储在文件中

(我尝试了泡菜,json,正常 f.write 但由于 .pprint() 的输出类型为 NONE 我直到现在才成功。(我我也是 python 的新手,同时学习 python 和 pyomo)。

None 的作品: '''

with open('some_file2.txt', 'w') as f:
    serializer.dump(x, f)

import pickle 
object = Object() 
filehandler = open('some_file', 'wb') 
pickle.dump(x, filehandler)

x = str(instance)
x = str(instance.pprint()) 
f = open('file6.txt', 'w')
f.write(x)
f.write(instance.pprint())
f.close()

pprint 方法使用 filename 关键字参数:

instance.pprint(filename='foo.txt')

instance.pprint() 在控制台中打印(标准输出的标准输出),但不 return 内容(如您所说,return 是 None)。要将其打印在文件中,您可以尝试将标准输出重定向到文件。

尝试:

import sys
f = open('file6.txt', 'w')
sys.stdout = f
instance.pprint()
f.close()

看起来 Bethany 有一个更干净的解决方案 =)

对我来说接受的答案不起作用,pprint 有不同的签名。

help(instance.pprint)
pprint(ostream=None, verbose=False, prefix='') method of pyomo.core.base.PyomoModel.ConcreteModel instance

# working for me:
        with open(path, 'w') as output_file:
            instance.pprint(output_file)