【发布时间】:2017-12-07 20:45:11
【问题描述】:
我需要针对 bash 脚本运行一系列 Python 源代码,该脚本包含检查全局变量是否存在的逻辑。我可以使用 2 个标准来查看变量是否是全局变量:
read file line by line
if there is an '=' (assignment sign) in the line AND no '#' in beginning of line (it is not commented out), check:
is there a 'def' string anywhere in the text above this assignment line, e.g. def function_name()?
if yes, variable within a function and hence not global
else, possible global variable
如何使用grep、awk 或sed 实现此伪代码?我也愿意接受有关使用 bash 脚本查找全局变量的更好策略的建议。
示例代码:
int a = 23
def func_name():
...body...
此代码未通过我们的测试。
示例代码2:
def function_name():
int a = 4
...
此代码通过测试。
【问题讨论】:
-
添加了 2 个示例以使问题更具体。
-
使用面向行的工具来分析 Python 源代码似乎是非常错误的,当有用 Python 编写的好的 Python 源代码分析器时。
-
按照说明实现这个伪代码很简单:你需要一个触发器,它最初是假的,一旦你遇到
def就设置为真,当你遇到结束时再次设置为假的功能。每当您看到=并且触发器为假时,您将其视为全局变量。当然,真正的问题已经存在于伪代码中:它偶尔会报告正确的全局变量,但也会给出误报并错过一些全局变量。 -
在不使用 python 的情况下考虑这种类型的事情很有趣,但如果您实际上是在实际安装了 python 的系统上解析已知安全的 python 代码,那也是不明智的。如果您不想运行代码(也许您是在网上找到的?)和/或本地没有安装 python,也许这是一个有趣的前提。看我的回答。