写入文件失败,但不生成错误 [英] Failed to write to file but generates no Error
问题描述
我试图写入一个文件,但它不工作。我经历了一步一步的调试(它去写命令,但是当我打开文件它是空的)。
我的问题是: 我怎样才能看到错误是什么,所以我可以调试?,试图写入文件时会出现什么问题,导致它的行为?。
$ b $
$ b $ sql $ c $ sql $ c $ sql $ c $ sql $ c $ sql $ c $ sql $ (errno,strerror):
printI / O error({0}):{1}格式(errno,strerror)
这应该很简单,但我似乎无法找到答案。另外,由于英文是第二语言,所以我提前道歉。
编辑:我在前面放了一个print语句,字符串不是空的。
Edit2:我使用Python 2.6,如果在某种程度上这个因素。
编辑3:我发现了一个解决方案,以我的错误。我决定尝试使用IDLE而不是PyCharm来运行我的脚本,它的工作方式就像一个魅力(双关语)。我不知道为什么,但那里是。任何理由为什么会发生?!
建立在克里斯·莫里斯的答案,也许做这样的事情:
$ try
sqlScript.write(sqlLine)
,
print str(e)
这将捕获抛出的任何异常(提供它的子类 Exception
,当然),并告诉你类型和错误信息。
另外,可以定义多个除了:
不同的可能的例外,所以也许可以尝试这样做,每个可能被抛出/引发的异常。
I'm trying to write to a file but it's not working. I've gone through step-by-step with the debugger (it goes to the write command but when I open the file it's empty).
My question is either: "How do I see what the error is so I can debug?", "What can go wrong when trying to write to a file that would cause it to behave this way?".
sqlScript = open('script-file.sql', 'a')
try:
sqlScript.write(sqlLine)
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
This should be simple but I can't seem to find an answer. Also, I apologize in advance as English is a second language.
Edit: I put a print statement just before and the string is not empty.
Edit2: I'm using python 2.6 if that factors in somehow.
Edit 3: I've found a "solution" to my error. I decided to try and run my script using IDLE instead of PyCharm and it works like a charm (pun intended). I have no clue why, but there it is. Any reason why that would happen?!
Building on Chris Morris' answer, maybe do something like this:
try:
sqlScript.write(sqlLine)
except Exception as e:
print type(e)
print str(e)
This will catch any Exception thrown (provided it's a subclass of Exception
, of course) and tell you the type and the error message.
Also, it's possible to define multiple except:
cases for different possible exceptions, so maybe try doing that for each exception that might be potentially thrown/raised.
这篇关于写入文件失败,但不生成错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!