如何在Python中通过__init__设置class变量?
How to set class variable through __init__ in Python?
我正在尝试在启动 scrapy 爬虫 (Python 3.7) 时从命令行更改设置。因此,我添加了一个 init 方法,但我不知道如何从 init[=25= 中更改 class 变量“延迟” ] 方法。
最小示例:
class testSpider(CrawlSpider):
custom_settings = {
'DOWNLOAD_DELAY': 10, # default value
}
""" get arguments passed over CLI
scrapyd usage: -d arg1=val1
scrapy usage: -a arg1=val1
"""
def __init__(self, *args, **kwargs):
super(testSpider, self).__init__(*args, **kwargs)
self.delay = kwargs.get('delay')
if self.delay:
testSpider.custom_settings['DOWNLOAD_DELAY'] = self.delay
print('init:', testSpider.custom_settings['DOWNLOAD_DELAY'])
print(custom_settings['DOWNLOAD_DELAY'])
不幸的是,这不会更改设置:
scrapy crawl test -a delay=5
10
init: 5
如何更改class变量?
I am trying to change setting from command line while starting a
scrapy crawler (Python 3.7). Therefore I am adding a init method...
...
scrapy crawl test -a delay=5
根据scrapy docs. (Settings/Command line options section)
需要使用 -s
参数来更新设置
scrapy crawl test -s DOWNLOAD_DELAY=5
无法通过init
或其他方法在爬虫代码运行时更新设置(详情见githubUpdate spider settings during runtime #4196
我正在尝试在启动 scrapy 爬虫 (Python 3.7) 时从命令行更改设置。因此,我添加了一个 init 方法,但我不知道如何从 init[=25= 中更改 class 变量“延迟” ] 方法。
最小示例:
class testSpider(CrawlSpider):
custom_settings = {
'DOWNLOAD_DELAY': 10, # default value
}
""" get arguments passed over CLI
scrapyd usage: -d arg1=val1
scrapy usage: -a arg1=val1
"""
def __init__(self, *args, **kwargs):
super(testSpider, self).__init__(*args, **kwargs)
self.delay = kwargs.get('delay')
if self.delay:
testSpider.custom_settings['DOWNLOAD_DELAY'] = self.delay
print('init:', testSpider.custom_settings['DOWNLOAD_DELAY'])
print(custom_settings['DOWNLOAD_DELAY'])
不幸的是,这不会更改设置:
scrapy crawl test -a delay=5
10
init: 5
如何更改class变量?
I am trying to change setting from command line while starting a scrapy crawler (Python 3.7). Therefore I am adding a init method...
...
scrapy crawl test -a delay=5
根据scrapy docs. (Settings/Command line options section) 需要使用
-s
参数来更新设置
scrapy crawl test -s DOWNLOAD_DELAY=5
无法通过
init
或其他方法在爬虫代码运行时更新设置(详情见githubUpdate spider settings during runtime #4196