在Python中读取config.js
我正在处理一个同时使用Java脚本和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 oconfig 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)
但它返回此
{'': '', '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': ''}
如您所见,它混合了两个数据库名称(没有‘omebase’,只有‘antherbase’)
有没有关于如何正确获取我的数据的想法? 谢谢:)
解决方案
我认为在这里使用节点访问者没有用处。
相反,递归地遍历整个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'"
}
}
}
相关文章