Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中从脚本到函数读取外部变量_Python_Python 3.x - Fatal编程技术网

在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没有全局变量。我们只有模块级字典,这是