英文:
How to catch the error message from Chem.MolFromSmiles('Formula')
问题
from rdkit import Chem
m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C')
m
try:
if m is None:
raise ValueError("Invalid chemical structure")
except Exception as e:
print(str(e))
英文:
I'm new to this rdkit, below is the code that I'm using to get the chemical image from the formula,
from rdkit import Chem
m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C')
m
if the code is correct, it displays the structre. The above code displays the error saying
"[15:23:55] Explicit valence for atom # 11 C, 5, is greater than permitted"
I tried adding try catch but, it does not help.
I need to catch this exception/Message and display it to the user.
How can we do this?Issue Image Here
try:
from rdkit import Chem
m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C')
m
except Exception as e:
print(e)
答案1
得分: 1
不是错误,而是警告。您的代码在执行该赋值时不会出错。因此,没有错误可捕获。
但是您的解决方案位于Chem.MolFromSmiles
的返回值中。如果它无法构建出SMILES的mol对象,它会返回None
,而当它成功地“处理SMILES”时,它会返回mol对象。
当然,您可以自己引发错误!
from rdkit import Chem
m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C')
if m is None:
print("嘿,用户,出现了错误!")
# 或者甚至引发一个错误:
if m is None:
raise ValueError("无法解释SMILES为mol对象")
我知道我的答案不够完整。我的解决方案没有向用户传达警告。我觉得这可能相当困难。如果有解决方案,可能可以利用logging
或warnings
包找到。我也对此很感兴趣,但迄今为止还没有成功。
英文:
It is not an Error, it is a Warning. Your code does not break doing that assignment. So there is no Error to catch.
But your solution lays within the return of Chem.MolFromSmiles
. If it fails to build a mol object of your SMILES it returns None
, whereas it returns the mol object when it manages to "deal with the SMILES properly".
For sure you can raise an error yourself!
from rdkit import Chem
m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C')
if m is None:
print("hey user, there was an error!")
# or even raise an error:
if m is None:
raise ValueError("Could not interpret SMILES to mol object")
I know my answer is lacking. My solution is not forwarding the warning to the user. I feel like it is quite hard to do. If there is a solution it might be found utilizing logging
or warnings
package. I would also be interested in that but couldn't manage so far myself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论