在某个地方,我是个白痴,但找不到。
我正在通过ODBC使用PostgreSQL数据库运行Python脚本。我正在尝试从数据库异常消息中提取有意义的部分。这是原始消息,并添加了换行符以提高可读性:
(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -2147467259), None)
请注意,此字符串中有两组括号。首先,我找到外部位置并将其切成薄片。这给出了预期的结果:
-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -2147467259), None
然后,据我所知,使用相同的代码,我去除了另一组括号以及括号之外的所有内容。这样得出的结果:
(0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -214746725
即使我以相同的方式使用find()方法的结果,两次都将开放括号添加到开放括号位置作为切片的起点,开放括号仍在此处。
这是代码:
print (errorString)
openParenLocation = errorString.find('(')
closeParenLocation = errorString.rfind(')')
strippedString = errorString[openParenLocation + 1:closeParenLocation]
openParenLocation = strippedString.find('(')
closeParenLocation = strippedString.rfind(')')
dbErrorString = errorString[openParenLocation + 1:closeParenLocation]
print (strippedString)
print ("{}, {}".format(openParenLocation, closeParenLocation))
print (dbErrorString)
这是原始输出,没有添加换行符:
(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -2147467259), None)
-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -2147467259), None
36, 191
(0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -214746725
使用更小的字符串的测试代码可以正常工作:
testString = "(abc(def)ghij)"
openParenLocation = testString.find('(')
closeParenLocation = testString.rfind(')')
strippedTestString = testString[openParenLocation + 1:closeParenLocation]
openParenLocation = strippedTestString.find('(')
closeParenLocation = strippedTestString.rfind(')')
finalTestString = strippedTestString[openParenLocation + 1:closeParenLocation]
非常感谢你。
解决方案
看起来像这行:
dbErrorString = errorString[openParenLocation + 1:closeParenLocation]
相反,应为:
dbErrorString = strippedString[openParenLocation + 1:closeParenLocation]