在 Python 阅读 config.js

Reading config.js in Python

我在一个同时使用 javascript 和 python 的项目中工作。我的 python 代码必须能够读取 config.js 文件并从那里获取 IP 地址、密码、主机.... 我无法以任何方式修改 config.js 文件。

我试过使用 slimit,但它混合了一些字段,所以我无法正确访问我的数据。可能是因为有些数据确实是嵌套的,通过config.js文件有很多评论。

配置文件看起来像这样(但实际上要长很多)

'use strict';

module.exports = {
    someconfig: {
        File: {
            path: '/some/path', // comment
            some_number: 50, // comment
        },
        Syslog: {
            path: '/some/other/path', // comment
            localhost: 'localhost', //comment
            app_name: 'somename', // comment
        },
        /**
        * some really
        * long
        * long
        * comment
        */
    },

    db: {
        mongoose: "5.0",
        servers: [{
            host: '1.1.1.1'
        }],
        database: 'somebase',  // comment
        user: 'myUserName',  //comment
        pass: 'myPassword',  // comment

        // some_comment

        config: {
            // some comment
            autoIndex: false
        },

        // lots of
        // comments
        // several lines

        someconfig: {
            // comment
            somevariable: "variable",
            anothervariable: "reallylongstring_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        },
    },

    anotherconfig: {
        very_nested: [{
            host: '1.1.1.1'
        }],
        database: 'anotherdatabase', // comment
        user: 'myUserName', // comment
        pass: 'myPassword', // comment
    },


};

我试过的代码是这样的

from slimit.parser import Parser

parser = Parser()
tree = parser.parse(open(r'C:\path\to\config copy.js').read())
fields = {getattr(node.left, 'value', ''): getattr(node.right, 'value', '')
          for node in nodevisitor.visit(tree)
          if isinstance(node, ast.Assign)}

print (fields)

但是returns这个

{'': '', 'someconfig': '', 'File': '', 'path': "'/some/other/path'", 'some_number': '50', 'Syslog': '',
 'localhost': "'localhost'", 'app_name': "'somename'", 'db': '', 'mongoose': '"5.0"',
 'servers': '', 'host': "'1.1.1.1'", 'database': "'anotherdatabase'",
 'user': "'myUserName'", 'pass': "'myPassword'", 'config': '', 'autoIndex': 'false', 'somevariable': '"variable"',
 'anothervariable': '"reallylongstring_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"',
 'anotherconfig': '', 'very_nested': ''}

如您所见,它混合了两个数据库名称('somebase' 不存在,只有 'anotherbase')

知道如何正确获取我的数据吗? 谢谢:)

我认为在这里使用 NodeVisitor 没有用。

相反,递归地遍历整个 AST 并从所有感兴趣的项目构建一个嵌套的字典。作为一个最小的实现,可以根据需要进行扩展:

from slimit.parser import Parser
from slimit import ast

parser = Parser()

with open(r'config.js', encoding='utf8') as js:
    tree = parser.parse(js.read())

def walk(node):
    if not isinstance(node, ast.Node): 
        return
    elif isinstance(node, ast.Program):
        # the Program node itself becomes a dict of its contained assignments
        items = [walk(child) for child in node.children()]
        # assignments can be recognized by the fact that they are (name, value) tuples
        return dict(i[0] for i in items if isinstance(i[0], tuple))
    elif isinstance(node, ast.Assign):
        # an Assignment node becomes a (name, value) tuple
        return walk(node.left), walk(node.right)
    elif isinstance(node, ast.DotAccessor):
        # a DotAccessor node becomes a string.joined.with.dots
        return '.'.join(walk(child) for child in node.children())
    elif isinstance(node, ast.Object):
        # an Object node becomes a dict
        return dict(walk(child) for child in node.children())
    elif isinstance(node, ast.Array):
        # an Array node becomes a list
        return list(walk(child) for child in node.children())
    elif isinstance(node, (ast.Identifier, ast.String, ast.Number, ast.Boolean)):
        # Indentifiers and primitives give their native values
        return node.value       
    return [walk(child) for child in node.children()]

result = walk(tree)
print(result)

生成一个应该易于处理的整齐嵌套的对象图:

{
    'module.exports': {
        'someconfig': {
            'File': {
                'path': "'/some/path'",
                'some_number': '50'
            },
            'Syslog': {
                'path': "'/some/other/path'",
                'localhost': "'localhost'",
                'app_name': "'somename'"
            }
        },
        'db': {
            'mongoose': '"5.0"',
            'servers': [{'host': "'1.1.1.1'"}],
            'database': "'somebase'",
            'user': "'myUserName'",
            'pass': "'myPassword'",
            'config': {'autoIndex': 'false'},
            'someconfig': {
                'somevariable': '"variable"',
                'anothervariable': '"reallylongstring_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"'
            }
        },
        'anotherconfig': {
            'very_nested': [{'host': "'1.1.1.1'"}],
            'database': "'anotherdatabase'",
            'user': "'myUserName'",
            'pass': "'myPassword'"
        }
    }
}