我有一个配置文件,其中定义了一些选项。有时,如果找不到请求的选项,我想忽略错误并返回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) 我的bash
(4.1) 目录堆栈通常有十几个或更多条目。我想替换dirs
with的输出dirs -v
,所以我再也不用玩“猜幻数”pushd
了。
我替换dirs
为dirs -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
输出现在可读的,但pushd
并popd
仍产生旧呕吐-的-斜线:
$ 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 …
在上段自定义类的Python语言参考它指出:
特殊属性:
__name__
是类名;__module__
是定义类的模块名称;__dict__
是包含类的命名空间的字典;__bases__
是包含基类的元组(可能是空的或单例),按它们在基类列表中出现的顺序排列;__doc__
是类的文档字符串,或者None
是未定义的.
那么,__bases__
对于自定义类可能"可能是空的"?如果所有内容都隐含object
在Python中继承,那怎么能实现3
呢?
一个空的唯一类__bases__
是object
本身:
>>> object.__bases__
()
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
据我所知,在 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)
我读了一些文章,但他们没有澄清我的问题。
我正在尝试制作桌面通知程序,为此我正在从网站上抓取新闻。当我运行程序时,出现以下错误。
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) 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
有用?为什么它会截断路径?
我很困惑,__str__
为类定义似乎对str
在类实例上使用该函数没有任何影响.例如,我在Django文档中读到:
该
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) 例如,我有一个字符串:
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) 我使用 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制作一个简单的文本游戏.我有一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解释器吐出的错误时遇到了问题.
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) 我在下面.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)
我哪里错了?
python ×9
java ×2
python-2.7 ×2
bash ×1
built-in ×1
class ×1
configparser ×1
exception ×1
inheritance ×1
methods ×1
os.path ×1
overloading ×1
popen ×1
python-2.x ×1
python-3.x ×1
regex ×1
string ×1
subprocess ×1
unicode ×1
xml ×1