如何使用Python

时间:2018-04-20 20:40:34

标签: python jsonnet

我正在使用jsonnet构建将由Python代码使用的json对象,使用bindings从Python调用jsonnet。我想设置我的目录结构,以便jsonnet文件位于相对于运行Python代码的子目录或子目录中,如:

foo.py jsonnet/ jsonnet/bar.jsonnet jsonnet/baz.libsonnet

运行foo.py应该可以使用_jsonnet.evaluate_snippet()jsonnet/中从jsonnet/导入其他文件的文件中读取的字符串。最好的方法是什么?

2 个答案:

答案 0 :(得分:3)

默认导入器使用相对于导入它们的文件的路径。如果是evaluate_snippet,您需要手动传递路径。这样jsonnet就知道在哪里查找导入的文件。

如果您打算处理文件,可以使用自定义导入程序。 (Digression:jsonnet试图避免需要预处理源文件,所以在jsonnet中可能有更好的方法或缺少的功能。)

以下是有关如何在Python中使用自定义导入程序的完整实用示例(根据提供的目录结构进行调整):

import os
import unittest

import _jsonnet


#  Returns content if worked, None if file not found, or throws an exception
def try_path(dir, rel):
    if not rel:
        raise RuntimeError('Got invalid filename (empty string).')
    if rel[0] == '/':
        full_path = rel
    else:
        full_path = dir + rel
    if full_path[-1] == '/':
        raise RuntimeError('Attempted to import a directory')

    if not os.path.isfile(full_path):
        return full_path, None
    with open(full_path) as f:
        return full_path, f.read()


def import_callback(dir, rel):
    full_path, content = try_path(dir, rel)
    if content:
        return full_path, content
    raise RuntimeError('File not found')


class JsonnetTests(unittest.TestCase):
    def setUp(self):
        self.input_filename = os.path.join(
            "jsonnet",
            "bar.jsonnet",
        )
        self.expected_str = '{\n   "num": 42,\n   "str": "The answer to life ..."\n}\n'
        with open(self.input_filename, "r") as infile:
            self.input_snippet = infile.read()

    def test_evaluate_file(self):
        json_str = _jsonnet.evaluate_file(
            self.input_filename,
            import_callback=import_callback,
        )
        self.assertEqual(json_str, self.expected_str)

    def test_evaluate_snippet(self):
        json_str = _jsonnet.evaluate_snippet(
            "jsonnet/bar.jsonnet",
            self.input_snippet,
            import_callback=import_callback,
        )
        self.assertEqual(json_str, self.expected_str)

if __name__ == '__main__':
    unittest.main()

注意:它是an example from jsonnet repo的修改版本。

答案 1 :(得分:1)

I don't fully get why you would use evaluate_snippet() (maybe mask the actual filenames via loading them from python into strings + evaluate_snippet("blah", str) ? ), instead of evaluate_file() - in any case that structure should just work ok.

Example:

jsonnet_test.py:

import json:
import _jsonnet

jsonnet_file = "jsonnet/bar.jsonnet"
data = json.loads(_jsonnet.evaluate_file(jsonnet_file))
print("{str} => {num}".format(**data))

jsonnet/bar.jsonnet:

local baz = import "baz.libsonnet";
{
  str: "The answer to life ...",
  num: baz.mult(6, 7),
}

jsonnet/baz.libsonnet:

{
  mult(a, b):: (
    a * b
  ),
}

Output:

$ python jsonnet_test.py
The answer to life ... => 42