在python中它是真的,except Exception as ex或者except BaseException as ex是相同except:但你得到了对异常的引用?
从我的理解BaseException是更新的默认全能.
除此之外,为什么你只想要一个except:条款?
我有一个从MongoDB返回数据库连接处理程序的函数.我有各种其他函数调用DB,我想让连接处理程序抛出一个函数,所以我不必在每个函数中定义它.
这看起来不错吗?我想我的问题是,如果它无法与数据库服务器建立连接,它将打印两条消息Could not connect to server,No hosts found我怎样才能打印"无法连接到服务器".
def mongodb_conn():
try:
conn = pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
return conn
def get_hosts()
try:
conn = mongodb_conn()
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
get_hosts()
Run Code Online (Sandbox Code Playgroud) 我希望该类与以下内容相同:
class Player:
def __init__(self, **kwargs):
try:
self.last_name = kwargs['last_name']
except:
pass
try:
self.first_name = kwargs['first_name']
except:
pass
try:
self.score = kwargs['score']
except:
pass
Run Code Online (Sandbox Code Playgroud)
但这看起来真的很草率.有没有更好的方法来定义这个__init__方法?我希望所有的关键字参数都是可选的.
Python 教程有一个名为 Errors and Exceptions 的部分,它使用结构作为;
try:
[statement]
except [Built-in ExceptionType]:
do something when an exception has been captured.
finally:
do something whether exception occurred or not.
Run Code Online (Sandbox Code Playgroud)
这也可以通过直接引发错误来处理。
try:
raise [Built-in ExceptionType]
except [Built-in ExceptionType above] as e:
print(f'foo error: {e}')
Run Code Online (Sandbox Code Playgroud)
有几个内置的 ExceptionType,良好的做法是开发人员应该捕获开发人员应该寻找的每个特定异常类型。(请参阅为什么“除了:通过”是一种糟糕的编程习惯?)
但是,在我阅读日志部分之后。我在想我想将错误记录到日志文件中,让用户知道错误(也许只是打印文本,用户可以通知 IT 支持),而不是在屏幕上抛出异常。因此,代替上面的 try / except 组合,我可以使用以下错误消息并记录下来。
if len(symbol) != 1:
error_message = f'Created box with symbol={symbol}, width={width} and height={height}, Symbol needs to be a string of length 1'
logger.error(error_message)
print(f'\nError! symbol={symbol}, width={width} and height={height} …Run Code Online (Sandbox Code Playgroud) 我的代码包含一个常规的try-except块。我下载了pycodestyle库以在我的代码上测试pep8。我测试了我的代码,并收到以下PEP8错误:
E722 do not use bare 'except'
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,我该如何解决?谢谢。
#!/usr/bin/python
try:
f = open("/home/masi/r.raw", "r+")
aBuf = f.seek(4)
except:
print "Error at position : ", position
events = []
for i in range(100):
aBuf = f.seek(4);
try:
if aBuf[:4] == b'\xFA\xFA\xFA\xFA':
print("E")
except:
# print "\0"
f.close()
Run Code Online (Sandbox Code Playgroud)
当我评论除了打印,我得到错误
f.close()
^
IndentationError: expected an indented block
Run Code Online (Sandbox Code Playgroud)
我想我需要尝试 - 除非因为if子句经常是假的.
为什么我会得到这种意外的压痕?
这些命令都不会检索函数的文档字符串并将其分配给变量.如何实现?
我尝试过各种各样的事 其中一个是help函数,但它似乎激活整个程序而不是返回一个字符串.我尝试了各种命令,但没有一个能够检索文档字符串.
import PIL
PILCommands=dir('PIL')
ListA=[]
ListB=[]
ListC=[]
ListD=[]
ListE=[]
LisfF=[]
ListG=[]
ListH=[]
for x in PILCommands:
print(x)
try:
ListA.append(x.__doc__)
except:
pass
try:
ListB.append(x.__doc__())
except:
pass
try:
ListC.append(str(x))
except:
pass
try:
ListD.append(help(x))
except:
pass
try:
ListE.append(eval("x.__doc__"))
except:
pass
try:
ListF.append(eval("inspect.getdoc(x)"))
except:
pass
try:
ListG.append(eval("dir(x)"))
except:
pass
try:
ListH.append(eval("PIL.x.__doc__"))
except:
pass
print
print("Command1: x.__doc__")
print(ListA)
print
print("Command1: x.__doc__()")
print(ListB)
print
print("Command1: str(x)")
print(ListC)
print
print("help(x)")
print(ListD)
print
print('Command1: eval("eval("x.__doc__")')
print(ListE)
print
print('Command1: eval("inspect.getdoc(x)")')
print(ListE)
print
print('Command1: eval("dir(x)")')
print(ListG) …Run Code Online (Sandbox Code Playgroud) 这是我脚本的一部分:
try:
read2length = len(reads[1])
x2 = data[read1length:read1length+read2length,0]
y2 = data[read1length:read1length+read2length,1]
fig = plt.figure()
plt.bar(x2,y2, align='center')
fig.suptitle('Read 2 Camera Timeouts', fontsize=20)
plt.xlabel('Cycle', fontsize=18)
plt.ylabel('#', fontsize=16)
if read2length < 50:
plt.xticks(x1, fontsize=14)
fig.savefig(join((path),'Read 2 Camera Timeouts.jpg'))
except: pass
try:
read3length = len(reads[2])
x3 = data[read1length+read2length:read1length+read2length+read3length,0]
y3 = data[read1length+read2length:read1length+read2length+read3length,1]
fig = plt.figure()
plt.bar(x3,y3, align='center')
fig.suptitle('Read 3 Camera Timeouts', fontsize=20)
plt.xlabel('Cycle', fontsize=18)
plt.ylabel('#', fontsize=16)
if read3length < 50:
plt.xticks(x1, fontsize=14)
fig.savefig(join((path),'Read 3 Camera Timeouts.jpg'))
except: pass
Run Code Online (Sandbox Code Playgroud)
我希望脚本尝试第一个和第二个.他们是否工作我希望脚本继续.
我一直得到read2length没有定义?
这是怎么回事?
我想确保输入数字.我已尝试使用符号和字母进行测试,但shell只会抛出一个错误,上面写着"Decimal的文字无效".我正在研究计算器,所以认为十进制模块最适合.提前致谢.
这是我的代码:
import decimal
while True:
userInput = (raw_input("Enter number:"))
try:
userInput = decimal.Decimal(userInput)
break
except ValueError:
print ("Number please")
Run Code Online (Sandbox Code Playgroud)
使用Python 2.7.6
我需要删除"u"前缀,因为我将这些json序列化列表传递到前端并使用javascript处理它们.Javascript无法理解这些"你".
这是代码:
context['list_of_dicts'] = serialize('json', my_list_of_dicts)
# this function is wrapped with a @json response decorator
Run Code Online (Sandbox Code Playgroud)
@json_response看起来像:
def json_response(func):
"""
A decorator thats takes a view response and turns it
into json. If a callback is added through GET or POST
the response is JSONP.
"""
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse):
return objects
try:
data = simplejson.dumps(objects)
if 'callback' in request.REQUEST:
# a jsonp response!
data = '%s(%s);' % (request.REQUEST['callback'], data)
return HttpResponse(data, …Run Code Online (Sandbox Code Playgroud) python ×10
python-2.7 ×3
django ×1
docstring ×1
except ×1
function ×1
javascript ×1
json ×1
module ×1
pep8 ×1
pymongo ×1
python-3.x ×1
try-catch ×1
unicode ×1
user-input ×1
while-loop ×1