简体   繁体   English

(Python)在一个模块中从__init__导入参数以在另一个模块中使用?

[英](Python) Import argument from __init__ in one module for use in another?

I'm really new to Python and have been using it in conjunction with Scrapy for making some web crawlers. 我对Python真的很陌生,并且一直与Scrapy结合使用它来制作一些Web搜寻器。 When running a spider from the terminal I can use "-a NAME=VALUE" to set arguments, which is especially useful for directing it to different domains. 从终端运行Spider时,我可以使用“ -a NAME = VALUE”设置参数,这对于将其定向到不同域特别有用。 I'm trying use the "domain" argument as a variable in another module but got stuck. 我正在尝试将“ domain”参数用作另一个模块中的变量,但被卡住了。 Here's a portion of the module I'm trying to import the argument from: 这是我要从中导入参数的模块的一部分:

class Spider(spiders.CrawlSpider):
    name = 'changelog'
    rules = (spiders.Rule(SgmlLinkExtractor(), callback='parse_item', follow=True),)

    def __init__(self, domain='WHAT_IM_TRYING_TO_FIND', *args, **kwargs):
        super(Spider, self).__init__(*args, **kwargs)
        self.domain = domain
        self.allowed_domains = [domain]
        self.start_urls = [
            'http://%s/' % domain,
            'http://%s/index.html' % domain,
            'http://%s/index.php' % domain,
        ]

In a separate module, trying things like 在单独的模块中,尝试类似

from MyModule import Spider

variable = Spider.domain

or 要么

variable = __import __ ('MyModule').Spider.domain

gives me 给我

Class 'Spider' has no 'domain' member

Any guidance will be greatly appreciated! 任何指导将不胜感激!

Scrapy's file structure looks like this: Scrapy的文件结构如下所示:

myproject/
__init __.py
items.py
pipelines.py
settings.py
spiders/
    __init __.py
    spider.py

domain is an attribute of instances of Spider, not of the Spider class. domain是Spider实例的属性,而不是Spider类的属性。 You can only access domain if you have an instance of Spider created somewhere. 如果您在某个地方创建了Spider实例,则只能访问domain

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM