2
我想用Python的Click library解析一些命令行參數,並將提供的值保存在對象中。使用Python的點擊庫保存命令行選項的值
我的第一個猜測是做這樣的:
import click
class Configuration(object):
def __init__(self):
# configuration variables
self.MyOption = None
# method call
self.parseCommandlineArguments()
@click.command()
@click.option('--myoption', type=click.INT, default=5)
def parseCommandlineArguments(self, myoption):
# save option's value in the object
self.MyOption = myoption
# create an instance
configuration = Configuration()
print(configuration.MyOption)
然而,這是不行的,而不是我得到:
TypeError: parseCommandlineArguments() takes exactly 2 arguments (1 given)
顯然,通過self
的裝飾功能不正確的方法來做到這一點。如果我從方法參數中刪除self
,那麼我可以做print(myoption)
,它會在屏幕上打印5
,但是我的Configuration()
類的任何實例都不會知道該值。
處理這個問題的正確方法是什麼?我認爲它與context handling in Click有關,但我無法根據提供的示例使其工作。