我正在研究一个python模块,该模块可获取,下载/更新然后自动安装其他模块。我该如何使用** kwargs(或替代方法),而无需在“ flags”系统最后使用= True?
我一般来说经验不是很丰富,所以不确定在这里做什么
当前,要使静默标志起作用,它必须看起来像这样:
pyup.imp(["psutil","shutil","os","sys","pyinstaller"],silent=True)
但是我希望调用函数看起来像这样:
pyup.imp(["psutil","shutil","os","sys","pyinstaller"],silent)
函数本身看起来像这样(在pyup.py中):
def imp(libs = [], *args, **kwargs):
其中libs []是包含所需库的数组。
如何使函数调用不需要“ = True”?
答案 0 :(得分:1)
如果要将一系列字符串标志传递给函数(好像它是终端应用程序),则可以通过*args
将它们作为未命名的位置参数传递。
def imp(libs=[], *args):
silent = '--silent' in args
# somewhere else
imp([...], '--silent')
答案 1 :(得分:0)
如果我们定义了这样的函数,则不能:
def imp(libs = [], *args, **kwargs):
但是,如果您这样定义函数,则可以:
def imp(libs = [], silent = True, *args, **kwargs):
实际上,正如您发布的那样,您可以毫无问题地运行该程序:
silent = True
imp(["psutils", ...], silent)
只有在函数内部,kwargs
永远不会拥有键silent
,因为它由另一个参数持有。