Reading config.js in Python(在Python中读取config.js)
本文介绍了在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'"
}
}
}
这篇关于在Python中读取config.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在Python中读取config.js
猜你喜欢
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01