草庐IT

python - `with` s 中有几个 `try` s

我有几个可能的文件可以保存我的数据;它们可以用不同的方式压缩,所以要打开它们我需要使用file()、gzip.GzipFile()和其他也返回一个文件对象(支持带接口(interface))。我想尝试每一个,直到一个成功打开,所以我可以做类似的事情try:withgzip.GzipFile(fn+'.gz')asf:result=process(f)except(IOError,MaybeSomeGzipExceptions):try:withxCompressLib.xCompressFile(fn+'.x')asf:result=process(f)except(IOError,M

python - 如何防止 try catch python中的所有可能行?

我连续有很多行可能会引发异常,但无论如何,它仍应继续下一行。如何在不单独trycatch每个可能引发异常的语句的情况下执行此操作?try:this_may_cause_an_exception()but_I_still_wanna_run_this()and_this()and_also_this()exceptException,e:logging.exception('Anerrormaybeoccuredinoneoffirstoccuringfunctionscausingtheothersnottobeexecuted.Locals:{locals}'.format(loca

python - Python *with* 语句是否完全等同于 try - (except) - finally block ?

我知道这已被广泛讨论,但我仍然找不到答案来确认这一点:with语句是否与在try-(except)-finallyblock中调用相同的代码相同,上下文管理器的__exit__函数中定义的任何内容都放在finallyblock中?例如--这2个代码片段是否在做完全相同的事情?importsysfromcontextlibimportcontextmanager@contextmanagerdefopen_input(fpath):fd=open(fpath)iffpathelsesys.stdintry:yieldfdfinally:fd.close()withopen_input("

python - 检查文件是否可以用 Python : try or if/else? 读取

我有以下代码:importglob,osforfileinglob.glob("\\*.txt"):ifos.access(file,os.R_OK):#Dosomethingelse:ifnotos.access(file,os.R_OK):print(file,"isnotreadable")else:print("Somethingwentwrongwithfile/dir",file)break但我不完全确定这是否是正确的做法。使用try和catch错误会更好吗?如果是这样,我该如何尝试以提高可读性?请注意我的else语句中的break。一旦无法读取文件,我就想中止循环。

python - 如何快速禁用 python 中的 try 语句进行测试?

假设我有以下代码:try:print'foo'#Alotmorecode...print'bar'except:pass出于测试目的,我如何临时禁用try-statement?你不能只注释掉try和except行,因为缩进仍然是关闭的。没有比这更简单的方法了吗?#try:print'foo'#Alotmorecode...print'bar'#except:#pass 最佳答案 您可以将异常重新引发为您的exceptblock的第一行,它的行为就像没有try/except一样。try:print'foo'#Alotmorecode.

python - 带有空 except 代码的 Try-except 子句

这个问题在这里已经有了答案:Howtoproperlyignoreexceptions(12个回答)关闭8年前。有时您不想在except部分中放置任何代码,因为您只想确保代码运行时没有任何错误,但对捕获它们不感兴趣。我可以在C#中这样做:try{do_something()}catch(...){}我怎么能在Python中做到这一点?,因为缩进不允许这样做:try:do_something()except:i_must_enter_somecode_here()顺便说一句,也许我在C#中所做的也不符合错误处理原则。如果您对此有任何想法,我将不胜感激。 最佳答

Python:try-except 作为表达式?

我发现自己一遍又一遍地有这种模式:variable=""try:variable=...dosomefileloadingstuff...except:variable=""有什么办法可以把它浓缩成一个表达式?与if-else语句一样,您可以转:variable=""ifsomething:variable=somethingelseelse:variable=""进入variable=somethingelseifsomethingelse""try-catch有什么等价的东西吗? 最佳答案 因为agf已经提供了我推荐的方法,所以

python - 在 try,catch,finally 语句中使用变量而不在外部声明它

我对Python很陌生,这是我正在查看的一些代码:try:connection=getConnection(database)cursor=connection.cursor()cursor.execute("somequery")except:log.error("Problem.")raisefinally:cursor.close()connection.close()清理得当吗?在我写过的其他语言中,我习惯做这样的事情:connection=Nonecursor=Nonetry:connection=getConnection(database)cursor=connectio

python - 如何在 try/except block 中公开变量?

如何在try/exceptblock中公开变量?importurllib.requesttry:url="http://www.google.com"page=urllib.request.urlopen(url)text=page.read().decode('utf8')except(ValueError,RuntimeError,TypeError,NameError):print("Unabletoprocessyourrequestdude!!")print(text)此代码返回错误NameError:name'text'isnotdefined如何使变量文本在try/exc

python - 如果 try 语句在 python 中成功,则运行代码

我想知道在python中是否有一种简单的方法来运行代码,如果try语句成功但不在try语句本身中。那是else或finally命令的作用吗(我不理解他们的文档)?我知道我可以使用这样的代码:successful=Falsetry:#codethatmightfailsuccessful=Trueexcept:#errorhandlingifcodefailedifsuccessful:#codetoruniftrywassuccessfulthatisn'tpartoftry但我想知道是否有更短的方法。 最佳答案 你想要else:f