我可以在调用 inner/decorated 函数时将参数传递到装饰器函数中吗?
Can I pass an argument into my decorator function when I call the inner/decorated function?
希望这个术语是正确的。我有这个装饰函数,它读取一个文本文件:
def read_commands(inner, path=BATCH_PATH):
with open(path) as f:
commands = ['python ' + line.replace('\n', '') for line in f]
def wrapper(*args, **kwargs):
for command in commands:
inner(command, *args, **kwargs)
return wrapper
这是它修饰的函数之一:
@read_commands
def execute_multi_commands(command, count):
LOG.info(f'Executing command {count}: {command}')
os.system(command)
count += 1
我希望能够在调用 execute_multi_commands
时更改默认路径,就像在我的 main
:
中一样
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--batch', action='store', type=str, dest='batch')
args = parser.parse_args()
count = 1
execute_multi_commands(count, path=args.batch)
但是,显然这不起作用,因为 path
不是 execute_multi_commands
中的参数。我可以在调用execute_multi_commands
时将path
传递给装饰器函数read_commands
吗? - 或者,更有可能,任何功能等效的替代品?
你不能,至少你的装饰器是这样写的。当你装饰一个函数时,它类似于做:
def execute_multi_commands(command, count):
LOG.info(f'Executing command {count}: {command}')
os.system(command)
count += 1
execute_multi_commands = read_commands(execute_multi_commands)
所以在这个点之后,read_commands
已经被执行了,文件也被读取了。
您可以做的是更改装饰器以读取包装器中的文件,例如:
def read_commands(inner, path=BATCH_PATH):
def wrapper(*args, **kwargs):
if "path" in kwargs:
path_ = kwargs.pop("path")
else:
path_ = path
with open(path_) as f:
commands = ['python ' + line.replace('\n', '') for line in f]
for command in commands:
inner(command, *args, **kwargs)
return wrapper
...但这意味着每次调用装饰函数时都读取文件,这与您之前所做的略有不同。
希望这个术语是正确的。我有这个装饰函数,它读取一个文本文件:
def read_commands(inner, path=BATCH_PATH):
with open(path) as f:
commands = ['python ' + line.replace('\n', '') for line in f]
def wrapper(*args, **kwargs):
for command in commands:
inner(command, *args, **kwargs)
return wrapper
这是它修饰的函数之一:
@read_commands
def execute_multi_commands(command, count):
LOG.info(f'Executing command {count}: {command}')
os.system(command)
count += 1
我希望能够在调用 execute_multi_commands
时更改默认路径,就像在我的 main
:
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-b', '--batch', action='store', type=str, dest='batch')
args = parser.parse_args()
count = 1
execute_multi_commands(count, path=args.batch)
但是,显然这不起作用,因为 path
不是 execute_multi_commands
中的参数。我可以在调用execute_multi_commands
时将path
传递给装饰器函数read_commands
吗? - 或者,更有可能,任何功能等效的替代品?
你不能,至少你的装饰器是这样写的。当你装饰一个函数时,它类似于做:
def execute_multi_commands(command, count):
LOG.info(f'Executing command {count}: {command}')
os.system(command)
count += 1
execute_multi_commands = read_commands(execute_multi_commands)
所以在这个点之后,read_commands
已经被执行了,文件也被读取了。
您可以做的是更改装饰器以读取包装器中的文件,例如:
def read_commands(inner, path=BATCH_PATH):
def wrapper(*args, **kwargs):
if "path" in kwargs:
path_ = kwargs.pop("path")
else:
path_ = path
with open(path_) as f:
commands = ['python ' + line.replace('\n', '') for line in f]
for command in commands:
inner(command, *args, **kwargs)
return wrapper
...但这意味着每次调用装饰函数时都读取文件,这与您之前所做的略有不同。