简体   繁体   English

将python输出为python可读格式

[英]Output python into python-readable format

We're using a python based application which reads a configuration file containing a couple of arrays: 我们使用的是基于python的应用程序,该应用程序读取包含几个数组的配置文件:

Example layout of config file: 配置文件的示例布局:

array1 = [
'bob',
'sue',
'jayne'
]

Currently changes to the configuration are done by hand, but I've written a little interface to streamline the process (mainly to avoid errors). 当前,对配置的更改是手动完成的,但是我编写了一个小界面来简化流程(主要是为了避免错误)。

It currently reads in the existing configuration, using a simple "import". 当前,它使用简单的“导入”读取现有配置。 However what I'm not sure how to do, is get my script to write it's output in valid python, so that the main application can read it again. 但是我不确定该怎么做,是让我的脚本将其写入有效的python输出中,以便主应用程序可以再次读取它。

How can I can dump the array back into the file, but in valid python? 如何使用有效的python将数组转储回文件中?

Cheers! 干杯!

I'd suggest JSON or YAML (Less verbose than JSON) for configuration files. 我建议配置文件使用JSONYAML (比JSON冗长)。 That way, the configuration file becomes more readable for the less pythonate ;) It's also easier to throw adequate errors, eg if the configuration is incomplete. 这样,配置文件对于pythonate越少就变得更具可读性;)例如,如果配置不完整,也容易引发足够的错误。

To save python objects you can always use pickle . 要保存python对象,您可以始终使用pickle

Generally using repr() will create a string that can be re-avaluated. 通常,使用repr()将创建可以重新计算的字符串。 But pprint does a little nicer output. 但是pprint的输出要好一些。

from pprint import pprint

outf.write("array1 = "); pprint(array1, outf)

repr(array1) (并将其写入文件)将是一个非常简单的解决方案,但它应该在这里工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM