小编Kev*_*ase的帖子

如何使 ConfigParser 返回默认值而不是引发 NoOptionError?

我有一个配置文件,其中定义了一些选项。有时,如果找不到请求的选项,我想忽略错误并返回None

setting.cfg

[Set]
ip=some_ip
verify=yes     #if verify does not exist here --> verify=None
Run Code Online (Sandbox Code Playgroud)

test.py

import sys
import ConfigParser

file="setting.cfg"

class ReadFile:
   def read_cfg_file(self):
      configParser = ConfigParser.RawConfigParser(allow_no_value=True)
      if os.path.isfile(file):
          configParser.read(file)
      else:
          sys.exit(1)
      try:
          verify = configParser.get('Set', 'verify')
      except ConfigParser.NoOptionError:
          pass

      return verify,and,lots,of,other,values
Run Code Online (Sandbox Code Playgroud)

如果我这样处理它,我将无法返回值,因为如果'verify'找不到该选项,它就会简单地传递。

如果找不到选项,有什么方法可以忽略错误,而是返回None

例如,这样的事情:

verify = configParser.get('Set', 'verify')
if not verify:
    verify=False
Run Code Online (Sandbox Code Playgroud)

python exception configparser python-2.7

5
推荐指数
2
解决办法
7582
查看次数

如何覆盖 pushd 和 popd 对目录的自动调用?

我的bash(4.1) 目录堆栈通常有十几个或更多条目。我想替换dirswith的输出dirs -v,所以我再也不用玩“猜幻数”pushd了。

我的部分解决方案

我替换dirsdirs -v使用执行的函数command

dirs()
{
    # "command" builtin prevents infinite recusion by suppressing lookup
    # of function and alias names.
    command dirs -v "${@}"
}
Run Code Online (Sandbox Code Playgroud)

(更新:根据气动学的建议,我现在使用builtin而不是command。它不能解决这个问题,但它稍微安全一些。)

dirs输出现在可读的,但pushdpopd仍产生旧呕吐-的-斜线

$ pushd ~/just/one/more/and/ill/quit/i/promise
~/just/one/more/and/ill/quit/i/promise ~/tmp/bash/bash-4.1...
may/give/rise/to/dom /oh/no/not/again /var/adm/log /omg/wt...
va/lang ~/doc/comp/java/api/java/util/regex barf barf barf...
Run Code Online (Sandbox Code Playgroud)

dirs用别名替换我的函数后,我得到了相同(缺乏)的结果:

alias dirs='command dirs -v "${@}"'
Run Code Online (Sandbox Code Playgroud)

解决方法

我终于得到了我想要通过重写输出pushd …

bash built-in bash-function

5
推荐指数
2
解决办法
659
查看次数

具有空__bases__属性的自定义类

在上段自定义类Python语言参考它指出:

特殊属性:__name__是类名; __module__是定义类的模块名称; __dict__是包含类的命名空间的字典; __bases__是包含基类的元组(可能是空的或单例),按它们在基类列表中出现的顺序排列; __doc__是类的文档字符串,或者None是未定义的.

那么,__bases__对于自定义类可能"可能是空的"?如果所有内容都隐含object在Python中继承,那怎么能实现3呢?

一个空的唯一类__bases__object本身:

>>> object.__bases__
()
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

python class python-3.x

5
推荐指数
1
解决办法
157
查看次数

静态和非静态方法的方法重载

据我所知,在 Java 方法重载中,我们对所有重载方法使用相同的名称。而且,它们的返回类型也不是问题。但是如果我们使用与静态和非静态形式相同的方法会发生什么,如下例所示?我们可以考虑这个方法重载吗?

class Adder {

    static int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

}
Run Code Online (Sandbox Code Playgroud)
class Test {

    public static void main(String[] args) {
        Adder a1 = new Adder();

        System.out.println(Adder.add(11, 11));

        System.out.println(a1.add(11, 11, 51));

    }
}
Run Code Online (Sandbox Code Playgroud)

我读了一些文章,但他们没有澄清我的问题。

java overloading

5
推荐指数
1
解决办法
4592
查看次数

AttributeError: 'xml.etree.ElementTree.Element' 对象没有属性 'encode'

我正在尝试制作桌面通知程序,为此我正在从网站上抓取新闻。当我运行程序时,出现以下错误。

news[child.tag] = child.encode('utf8')
AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)

我该如何解决?我对此完全陌生。我尝试寻找解决方案,但没有一个对我有用。

这是我的代码:

import requests
import xml.etree.ElementTree as ET


# url of news rss feed
RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml"


def loadRSS():
    '''
    utility function to load RSS feed
    '''
    # create HTTP request response object
    resp = requests.get(RSS_FEED_URL)
    # return response content
    return resp.content


def parseXML(rss):
    '''
    utility function to parse XML format rss feed
    '''
    # create element tree root object
    root = ET.fromstring(rss)
    # create empty list for news …
Run Code Online (Sandbox Code Playgroud)

python xml python-requests

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

如何/在哪里使用os.path.sep?

os.path.sep 是操作系统用于分隔路径名组件的字符.

但是当os.path.sep使用时os.path.join(),为什么它会截断路径?

例:

而不是'home/python',os.path.join返回'/python':

>>> import os
>>> os.path.join('home', os.path.sep, 'python')
'/python'
Run Code Online (Sandbox Code Playgroud)

我知道os.path.join()隐式插入目录分隔符.

哪里os.path.sep有用?为什么它会截断路径?

python os.path

4
推荐指数
1
解决办法
6991
查看次数

如何在不引发UnicodeEncodeError的情况下覆盖str函数?

我很困惑,__str__为类定义似乎对str在类实例上使用该函数没有任何影响.例如,我在Django文档中读到:

print语句和str内置的通话__str__(),以确定对象的人类可读表示.

但这似乎不是真的.以下是模块中的示例,其中text始终假定为unicode:

import six

class Test(object):

    def __init__(self, text):
        self._text = text

    def __str__(self):
        if six.PY3:
            return str(self._text)
        else:
            return unicode(self._text)

    def __unicode__(self):
        if six.PY3:
            return str(self._text)
        else:
            return unicode(self._text)
Run Code Online (Sandbox Code Playgroud)

在Python 2中,它提供以下行为:

>>> a=Test(u'café')
>>> print a.__str__()
café
>>> print a # same error with str(a)
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-63-202e444820fd> in <module>()
----> 1 str(a)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in …
Run Code Online (Sandbox Code Playgroud)

python unicode python-2.x

4
推荐指数
1
解决办法
837
查看次数

如何用匹配的转换替换重新匹配?

例如,我有一个字符串:

The struct-of-application and struct-of-world
Run Code Online (Sandbox Code Playgroud)

使用re.sub,它将用预定义的字符串替换匹配项。如何用匹配内容的转换替换匹配?要获取,例如:

The [application_of_struct](http://application_of_struct) and [world-of-struct](http://world-of-struct)
Run Code Online (Sandbox Code Playgroud)

如果我编写了一个简单的正则表达式((\w+-)+\w+)并尝试使用re.sub,则似乎无法使用匹配的内容作为替换的一部分,更不用说编辑匹配的内容了:

In [10]: p.sub('struct','The struct-of-application and struct-of-world')
Out[10]: 'The struct and struct'
Run Code Online (Sandbox Code Playgroud)

python regex

4
推荐指数
1
解决办法
1055
查看次数

使用 Popen.communicate 时,如何将警告与 stderr 中发现的错误分开?

我使用 Pythonsubprocess.Popen来执行命令并捕获其输出:

p = Popen(cmd, stdout=PIPE, stderr=PIPE,shell=True)
stdout, stderr = p.communicate()
Run Code Online (Sandbox Code Playgroud)

我想stderr在出现错误时告诉用户并退出我的脚本:

if stderr !='':
    return {'error':stderr}
Run Code Online (Sandbox Code Playgroud)

但是现在我发现stderr可以包含可以安全忽略的警告,所以我的脚本不应该退出,而是继续完成工作。

有没有办法将警告与错误分开stderr

python subprocess popen

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

有没有办法在实例化之前引用类对象?

我正在尝试使用Python制作一个简单的文本游戏.我有一Room节课:

class Room():
    def __init__(self, monster, exits, loot):
        self.room_guard = monster
        self.exits = exits
        self.guard_is_alive = True
        self.loot = loot
Run Code Online (Sandbox Code Playgroud)

当我创建房间时,我收到一个错误,因为我在创建之前调用它们是这样的:

room_2 = Room(spider, {"West": room_3, "East": room_4, "South": room_1}, 2)
room_1 = Room(trogdor, {"North": room_2}, 2)
Run Code Online (Sandbox Code Playgroud)

2号房间没有,"South": room_1因为它还没有实例化.有没有解决的办法?

python python-2.7

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

从基类扩展方法时的TypeError

我试图测试一个简单的Python继承案例,但我在理解Python解释器吐出的错误时遇到了问题.

class Mainclass(object):
    """
     Class to test the inheritance
    """
    def __init__(self,somevalue):
        self.somevalue = somevalue
    def display(self):
        print(self.somevalue)


class Inherited(Mainclass):
    """
    Inherited class from the Main Class
    """
    def display(self):
        print("**********")
        Mainclass.display()
        print("**********")

c = Inherited(100)
c.display()
Run Code Online (Sandbox Code Playgroud)

我只是试图在Inherited类中显示的输出中添加星号,那么为什么它会因以下错误而失败?

Traceback (most recent call last):
line 21, in <module>
c.display()
line 17, in display
Mainclass.display()
TypeError: display() missing 1 required positional argument: 'self'
Run Code Online (Sandbox Code Playgroud)

python methods inheritance

0
推荐指数
1
解决办法
38
查看次数

String.equals比较无法匹配

我在下面.equals用于String比较,但x不匹配"OU":

String memberOfValue="CN=cn,?OU=ou,?OU=roles,?OU=de,?OU=apps,?DC=meta,?DC=cc,?DC=com";
String[] pairs = memberOfValue.split(",");
for (int i=0;i<pairs.length;i++) {
    String pair = pairs[i];
    String[] keyValue = pair.split("=");
    System.out.println(keyValue[0]);
    String x = keyValue[0];
    String y = "OU";
    System.out.println(x);
    System.out.println(x.equals(y));
}
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

java string string-comparison

0
推荐指数
1
解决办法
520
查看次数