python - pyparsing 语法以提取 Python 片段的部分
问题描述
我有一个 Python 片段,如下所示:
fn = HiveExecOperator(
task_id="abc",
hql="abc.hql",
dq_sql=DQCheck("pqr")
.is_within_range(
"COUNT(DISTINCT billing_association_type)",
"type_cnts",
lower=1.0,
upper=float("inf"),
)
.build(),
dag=main_dag,
)
我想定义一个语法,它可以让我查看函数参数列表中的键值对,HiveExecOperator
而不会破坏嵌套的键值对。例如 - 我有兴趣取回一个列表:
[task_id="abc",
hql="abc.hql",
...
dq_sql=DQCheck("pqr")
.is_within_range(
"COUNT(DISTINCT billing_association_type)",
"type_cnts",
lower=1.0,
upper=float("inf"),
)
.build(),
...]
我尝试执行以下操作:
assignment = variable + '=' + "HiveExecOperator" + nestedExpr('(', ')').setParseAction(lambda x: print(x))
parameters.transformString(python_snippet)
输出setParseAction
为:
['fn', '=', 'HiveExecOperator(']
['task_id', '=', '"abc",']
['hql', '=', '"abc.hql",']
['dq_sql', '=', 'DQCheck("stage.billing_associations")']
['lower', '=', '1.0,']
['upper', '=', 'float("inf"),']
...
任何帮助将不胜感激。
解决方案
正如 mkrieger1 所说,您可以使用ast
内置的 Python 库。
在 Python 3.9(或更高版本)中,有可以将转换为字符串的ast.unparse
函数。ast.Node
import ast
mycode = """\
fn = HiveExecOperator(
task_id="abc",
hql="abc.hql",
dq_sql=DQCheck("pqr")
.is_within_range(
"COUNT(DISTINCT billing_association_type)",
"type_cnts",
lower=1.0,
upper=float("inf"),
)
.build(),
dag=main_dag,
)
"""
root = ast.parse(mycode)
calls = [n for n in ast.walk(root) if isinstance(n, ast.Call)]
first_call = calls[0]
target_list = [(k.arg, ast.unparse(k.value)) for k in first_call.keywords]
print(target_list)
这使
[
('task_id', "'abc'"),
('hql', "'abc.hql'"),
('dq_sql', "DQCheck('pqr').is_within_range('COUNT(DISTINCT billing_association_type)', 'type_cnts', lower=1.0, upper=float('inf')).build()"),
('dag', 'main_dag')
]
推荐阅读
- javascript - Angular 7 - 为桌面聊天界面设计组件的有效方法?
- odoo - Odoo 在产品代码和产品条形码中设置序列
- javascript - 无法使用 AJAX 和 codeigniter 从表中获取数据
- r - 如何遍历 R 中 data.table 中的列并创建一个包含汇总统计信息的新表?
- matlab - 关于支持向量回归的特征选择问题
- javascript - 在 Django www.example.com/?rcode=1 类型 url 中不起作用
- r - 将一个数据帧中的行替换为另一个数据帧中的行
- node.js - 如何在生产模式下运行 express-generator 创建的应用程序?
- cassandra - 假设我将一条记录写入 cassandra 集群,并立即读取它。cassandra如何保证我读到的就是我刚刚写的最新结果?
- html - 提交表单后如何编辑谷歌表格 HTML UI 元素?