在python中从脚本到函数读取外部变量
我在在python中从脚本到函数读取外部变量,python,python-3.x,Python,Python 3.x,我在Linux中有以下项目结构 main_project ├── base_dir │ └── helper │ └── file_helper.py │ └── __init__.py └── jobs └── adhoc_job.py └── __init__.py └── test_job.py └── __init__.py 在helper/file\u helper.py脚
Linux
中有以下项目结构
main_project
├── base_dir
│ └── helper
│ └── file_helper.py
│ └── __init__.py
└── jobs
└── adhoc_job.py
└── __init__.py
└── test_job.py
└── __init__.py
在helper/file\u helper.py
脚本中,我有下面的代码块
def null_cols_exception(df, cols_to_check):
"""
:param df: data frame on which the function has to be applied
:param cols_to_check: columns to check
:return:
"""
for i in cols_to_check:
excpt_cd = globals()[i + '_null_exception_code']
print(excpt_cd)
# There is some logic here but for test purpose removed it
# Here the data gets overwritten in LOOP I have covered that scenario but for test purpose removed it
现在我正在使用这个函数jobs/adhoc\u job.py
script
from helper.file_helper import null_cols_exception
test_col_null_exception_code = 123
test_col2_null_exception_code = 999
null_cols = ['test_col', 'test_col2']
# calling the null_cols_exception function
null_df = null_cols_exception(test_df, null_cols)
现在,当我运行jobs/adhoc\u job.py
脚本时
from helper.file_helper import null_cols_exception
test_col_null_exception_code = 123
test_col2_null_exception_code = 999
null_cols = ['test_col', 'test_col2']
# calling the null_cols_exception function
null_df = null_cols_exception(test_df, null_cols)
我在下面的点上得到下面的错误
excpt_cd = globals()[i + '_null_exception_code']
KeyError: 'test_col_null_exception_code'
基本上,函数无法派生test\u col\u null\u exception\u code
变量
如何解决此问题globals()
只知道自己模块中的globals
来自(我的):
返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法中,这是定义它的模块,而不是调用它的模块)
如果你想走那条路,你就得把球传过去
# calling the null_cols_exception function
null_df = null_cols_exception(None, null_cols, globals())
及
输出:
123
999
但是你最好使用列表/记录来保存你的对象,然后将其传递给其他人
参考:globals()
只知道自己模块中的globals
来自(我的):
返回表示当前全局符号表的字典。这始终是当前模块的字典(在函数或方法中,这是定义它的模块,而不是调用它的模块)
如果你想走那条路,你就得把球传过去
# calling the null_cols_exception function
null_df = null_cols_exception(None, null_cols, globals())
及
输出:
123
999
但是你最好使用列表/记录来保存你的对象,然后将其传递给其他人
参考资料:为什么要使用全局变量?Python没有全局变量。我们只有模块级字典,这就是为什么要使用globals返回的结果?Python没有全局变量。我们只有模块级字典,这是