【问题标题】:Determine type of element from list从列表中确定元素的类型
【发布时间】:2020-03-30 00:37:02
【问题描述】:

我的 python 代码正在使用 PEM 包读取包含证书和私钥的 PEM 文件。

代码:

import pem
Mylist = pem.parse_file(r"C:\Desktop\MyPemFile.pem")
for ele in Mylist:
     print(type(ele))

输出:

<class 'pem._core.RSAPrivateKey'>
<class 'pem._core.Certificate'>
<class 'pem._core.Certificate'>
<class 'pem._core.Certificate'>
<class 'pem._core.Certificate'> 

现在,我正在尝试从列表中识别每个元素的类型并执行某些操作。
但是,我无法确定类型。如何修改我的代码以确定每个元素的类型?

代码:

Mylist = pem.parse_file(r"C:\Desktop\MyPemFile.pem")
for ele in Mylist:
     if type(ele) == 'pem._core.RSAPrivateKey':
             print(ele) # Control doesn't go here. 
     else:
             print("Invalid type")

输出:

Invalid type
Invalid type
Invalid type
Invalid type
Invalid type 

【问题讨论】:

  • isinstance 是检查类(或子类)的常用工具

标签: python pem


【解决方案1】:

应该有一种简单的方法可以从pem 导入类型本身(而不是字符串标识符)。可能类似于from pem import RSAPrivateKey(我从未使用过该库)。那么你可以这样做:

if isinstance(ele, RSAPrivateKey):
    print(ele)

【讨论】:

  • 知道了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 2021-11-19
  • 2016-04-28
  • 2010-09-25
相关资源
最近更新 更多