[英]How to pass a parameter list to another function in Python?
使用optparse
,我想將選項列表參數的列表與調用add_option()的位置分開。 如何將內容打包到文件A中(然后解壓縮到文件B中),以便可以正常工作? parser_options.append()行將無法正常運行...
檔案A:
import file_b
parser_options = []
parser_options.append(('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable'))
parser_options.append(('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test. Decimals OK'))
my_object = file_b.B(parser_options)
文件B接收parser_options作為輸入:
import optparse
class B:
def __init__(self, parser_options):
self.parser = optparse.OptionParser('MyTest Options')
if parser_options:
for option in parser_options:
self.parser.add_option(option)
*編輯:固定使用ojbects
與其嘗試將您的選項添加到某種數據結構中,不如在文件A中定義一個向您提供的解析器添加選項的函數更簡單嗎?
檔案A:
def addOptions(parser):
parser.add_option('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable')
parser.add_option('-d', '--duration', type='string', dest='duration', default='', help='Number of hours to run the test. Decimals OK')
檔案B:
import optparse
def build_parser(parser_options):
parser = optparse.OptionParser('MyTest Options')
if parser_options:
parser_options(parser)
別處:
import file_a
import file_b
file_b.build_parser(file_a.addOptions)
您遇到的問題是您試圖在元組中傳遞關鍵字參數。 代碼('-b', '--bootcount', type='string', dest='bootcount', default='', help='Number of times to repeat booting and testing, if applicable')
是合法的在函數調用中,而不是其他任何地方。 在元組中, type='string'
位不合法!
如果要傳遞函數參數,則需要使用列表或元組作為位置參數,並使用字典作為關鍵字參數。 這是您可以通過將單個元組更改為包含args
元組和kwargs
字典的元組的方法:
parser_options = []
parser_options.append((('-b', '--bootcount'),
dict(type='string', dest='bootcount', default='',
help='Number of times to repeat booting and testing, if applicable')))
parser_options.append((('-d', '--duration'),
dict(type='string', dest='duration', default='',
help='Number of hours to run the test. Decimals OK')))
在另一個文件中,可以使用*
和**
運算符將元組和dict的內容傳遞給適當的函數,以解壓縮參數:
class B:
def __init__(self, parser_options)
self.parser = optparse.OptionParser('MyTest Options')
if parser_options:
for args, kwargs in parser_options:
self.parser.add_option(*args, **kwargs)
我最終在構造時將解析器傳遞給對象,這很好,因為可以從調用模塊中對其進行命名:
import optparse
parser = optparse.OptionParser('My Diagnostics')
parser.add_option('-p', '--pbootcount', type='string', dest='pbootcount', default='testing1234', help=' blah blah')
c = myobject.MyObject(parser)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.