是否可以创建依赖于上下文的函数?

问题描述 投票:0回答:1

我已经使用以下脚本直接运行脚本,只是为了在脚本外部运行bash命令行(例如作业调度程序)。

def qsubcommand(func):
    def wrapper(*args, **kwargs):
        if kwargs.get('test', False):
            cmdl = ' '.join(['this.py', func.__name__, *map(str, args)])
            return cmdl
        else:
            return func(*args, **kwargs)
    return wrapper

@qsubcommand
def calculate(value1, value2):
   # do something

if __name__ == '__main__':
    if len(sys.argv) > 1:
        func, args = sys.argv[1], sys.argv[2:]
        if func in locals().keys():
            locals()[func](*args)
        else:
            raise NotImplementedError

我有很多像'计算'这样的函数。我正在使用脚本来运行和测试程序。

# When I want to run directly:
>>> calculate(4, 5)

# When I want to just print command line:
>>> calculate(4, 5, test=True)
'this.py calculate 4 5'

但是,我想以与上下文相关的方式使用它。

# When I want to run directly:
>>> test = False
>>> calculate(4, 5)

# When I want to just print command line:
>>> test = True
>>> calculate(4, 5)
'this.py calculate 4 5'

如何修改让函数识别范围外的变量。是否可以访问函数外部的变量?

感谢您提前得到答复。

python decorator qsub
1个回答
1
投票

只需将其放在要检查变量的函数部分:

if 'test' in globals() and test:
    # do test
else:
    # do normal

函数总是可以访问函数作用域之外的变量,如果不使用global关键字,它们就无法编辑它们。

© www.soinside.com 2019 - 2024. All rights reserved.