小编war*_*iuc的帖子

XPath - 在某个节点之后选择文本

我找到了一个节点,现在我需要在它之后选择兄弟文本:

在此输入图像描述

在我的情况下,我需要得到文本 : 10 January

我该怎么做呢?

xpath

26
推荐指数
1
解决办法
2万
查看次数

在Python中只匹配一个unicode字母

我有一个字符串,我想从中提取3组:

'19 janvier 2012' -> '19', 'janvier', '2012'
Run Code Online (Sandbox Code Playgroud)

月份名称可能包含非ASCII字符,因此[A-Za-z]对我不起作用:

>>> import re
>>> re.search(ur'(\d{,2}) ([A-Za-z]+) (\d{4})', u'20 janvier 2012', re.UNICODE).groups()
(u'20', u'janvier', u'2012')
>>> re.search(ur'(\d{,2}) ([A-Za-z]+) (\d{4})', u'20 février 2012', re.UNICODE).groups()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
>>> 
Run Code Online (Sandbox Code Playgroud)

我可以使用,\w但它匹配数字和下划线:

>>> re.search(ur'(\w+)', u'février', re.UNICODE).groups()
(u'f\xe9vrier',)
>>> re.search(ur'(\w+)', u'fé_q23vrier', re.UNICODE).groups()
(u'f\xe9_q23vrier',)
>>> 
Run Code Online (Sandbox Code Playgroud)

我尝试使用[:alpha:],但它不起作用:

>>> re.search(ur'[:alpha:]+', u'février', re.UNICODE).groups()
Traceback (most recent call last):
  File "<stdin>", …
Run Code Online (Sandbox Code Playgroud)

python regex unicode character-properties

26
推荐指数
1
解决办法
9812
查看次数

获得完整的追溯

如何在以下情况下获得完整的回溯,包括调用func2func函数?

import traceback

def func():
    try:
        raise Exception('Dummy')
    except:
        traceback.print_exc()

def func2():
    func()


func2()
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

Traceback (most recent call last):
  File "test.py", line 5, in func
    raise Exception('Dummy')
Exception: Dummy
Run Code Online (Sandbox Code Playgroud)

traceback.format_stack()不是我想要的,因为需要将traceback对象传递给第三方模块.

我对这个案子特别感兴趣:

import logging


def func():
    try:
        raise Exception('Dummy')
    except:
        logging.exception("Something awful happened!")


def func2():
    func()


func2()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我得到:

ERROR:root:Something awful happened!
Traceback (most recent call last):
  File "test.py", line 9, in func
    raise Exception('Dummy')
Exception: Dummy
Run Code Online (Sandbox Code Playgroud)

python traceback

25
推荐指数
2
解决办法
2万
查看次数

QWidget调整大小信号?

我想在调整小部件大小时采取行动.

有没有办法在没有在该窗口小部件上安装事件过滤器的情况下捕获它(显然,没有子类化它)?AFAIK,QWidget没有resized信号.

qt qt4 pyqt pyqt4

23
推荐指数
4
解决办法
3万
查看次数

修补函数的__call__

我需要在测试中修补当前的日期时间.我正在使用这个解决方案:

def _utcnow():
    return datetime.datetime.utcnow()


def utcnow():
    """A proxy which can be patched in tests.
    """
    # another level of indirection, because some modules import utcnow
    return _utcnow()
Run Code Online (Sandbox Code Playgroud)

然后在我的测试中我做了类似的事情:

    with mock.patch('***.utils._utcnow', return_value=***):
        ...
Run Code Online (Sandbox Code Playgroud)

但今天我想到了一个想法,我可以通过修补__call__功能utcnow而不是额外的功能来简化实现_utcnow.

这对我不起作用:

    from ***.utils import utcnow
    with mock.patch.object(utcnow, '__call__', return_value=***):
        ...
Run Code Online (Sandbox Code Playgroud)

如何优雅地做到这一点?

python time mocking python-mock

21
推荐指数
2
解决办法
2559
查看次数

从子类主体访问父类属性

我有一个Klass类属性的类my_list.我有一个子类SubKlass,我希望有一个类属性my_list,它是父类中相同属性的修改版本:

class Klass():
    my_list = [1, 2, 3]


class SubKlass(Klass):
    my_list = Klass.my_list + [4, 5] # this works, but i must specify parent class explicitly
    #my_list = super().my_list + [4, 5] # SystemError: super(): __class__ cell not found
    #my_list = my_list + [4, 5] # NameError: name 'my_list' is not defined 


print(Klass.my_list)
print(SubKlass.my_list)
Run Code Online (Sandbox Code Playgroud)

那么,有没有办法访问父类属性而不指定其名称?

更新:

Python问题跟踪器上有一个错误:http://bugs.python.org/issue11339.我们希望它能在某个时刻得到解决.

python python-3.x

20
推荐指数
1
解决办法
8954
查看次数

使用mongoengine进入mongodb的多文档插入

在我的烧瓶应用程序中,我使用的是MongoeEgine.我正在尝试将多个文档插入到我的MongoDB中的places集合中.

我的文档类定义为

class places(db.Document):

  name = db.StringField(max_length=200, required=True)    
  loc = db.GeoPointField(required=True)

  def __unicode__(self):
    return self.name

    a=[]
    a.append({"name" : 'test' , "loc":[-87,101]})
    a.append({"name" : 'test' , "loc":[-88,101]})
    x= places(a)
Run Code Online (Sandbox Code Playgroud)

最后一个声明失败了

x= places(a)
TypeError: __init__() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)

我也尝试将其保存到我的实例中

places.insert(x)
places.save(x)
Run Code Online (Sandbox Code Playgroud)

都失败了.请帮忙.

python mongodb mongoengine flask

20
推荐指数
2
解决办法
1万
查看次数

Python Scrapy:将相对路径转换为绝对路径

我根据这里伟大人士提供的解决方案修改了代码; 我在这里得到了代码下面显示的错误.

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from dmoz2.items import DmozItem

class DmozSpider(BaseSpider):
   name = "namastecopy2"
   allowed_domains = ["namastefoods.com"]
   start_urls = [
    "http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=1",
    "http://www.namastefoods.com/products/cgi-bin/products.cgi?Function=show&Category_Id=4&Id=12",    

]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('/html/body/div/div[2]/table/tr/td[2]/table/tr')
    items = []
    for site in sites:
        item = DmozItem()
        item['manufacturer'] = 'Namaste Foods'
        item['productname'] = site.select('td/h1/text()').extract()
        item['description'] = site.select('//*[@id="info-col"]/p[7]/strong/text()').extract()
        item['ingredients'] = site.select('td[1]/table/tr/td[2]/text()').extract()
        item['ninfo'] = site.select('td[2]/ul/li[3]/img/@src').extract()
        #insert code that will save the above image path …
Run Code Online (Sandbox Code Playgroud)

python imagesource scrapy

19
推荐指数
3
解决办法
2万
查看次数

Decorator打印函数调用详细信息 - 参数名称和有效值

我想创建一个函数,作为另一个函数的装饰器将打印该函数调用细节 - 参数名称和有效值.我目前的实施是这样的.

def describeFuncCall(func):
    '''Decorator to print function call details - parameters names and effective values'''
    def wrapper(*func_args, **func_kwargs):
        print 'func_code.co_varnames =', func.func_code.co_varnames
        print 'func_code.co_argcount =', func.func_code.co_argcount
        print 'func_args =', func_args
        print 'func_kwargs =', func_kwargs
        params = []
        for argNo in range(func.func_code.co_argcount):
            argName = func.func_code.co_varnames[argNo]
            argValue = func_args[argNo] if argNo < len(func_args) else func.func_defaults[argNo - func.func_code.co_argcount]
            params.append((argName, argValue))
        for argName, argValue in func_kwargs.items():
            params.append((argName, argValue))
        params = [ argName + ' = ' + repr(argValue) for argName, argValue in …
Run Code Online (Sandbox Code Playgroud)

python

15
推荐指数
3
解决办法
1万
查看次数

芹菜任务和自定义装饰

我正在使用django和芹菜(django-celery)开展一个项目.我们的团队决定将所有数据访问代码(app-name)/manager.py包装在内(不要像管理员那样包装django),让(app-name)/task.py中的代码只处理汇编和执行芹菜任务(所以我们没有django此层中的ORM依赖项).

在我manager.py,我有这样的事情:

def get_tag(tag_name):
    ctype = ContentType.objects.get_for_model(Photo)
    try:
        tag = Tag.objects.get(name=tag_name)
    except ObjectDoesNotExist:
        return Tag.objects.none()
    return tag

def get_tagged_photos(tag):
    ctype = ContentType.objects.get_for_model(Photo)
    return TaggedItem.objects.filter(content_type__pk=ctype.pk, tag__pk=tag.pk)

def get_tagged_photos_count(tag):
    return get_tagged_photos(tag).count()
Run Code Online (Sandbox Code Playgroud)

在我的task.py中,我喜欢将它们包装成任务(然后可能使用这些任务来完成更复杂的任务),所以我写这个装饰器:

import manager #the module within same app containing data access functions

class mfunc_to_task(object):
    def __init__(mfunc_type='get'):
        self.mfunc_type = mfunc_type

    def __call__(self, f):
        def wrapper_f(*args, **kwargs):
            callback = kwargs.pop('callback', None)

            mfunc = getattr(manager, f.__name__)

            result = mfunc(*args, **kwargs)
            if callback:
                if self.mfunc_type == 'get':
                    subtask(callback).delay(result)
                elif …
Run Code Online (Sandbox Code Playgroud)

python django decorator celery django-celery

15
推荐指数
2
解决办法
1万
查看次数