如何评估PEP-508样式的平台标记?

时间:2018-11-21 17:54:45

标签: python pip

我想以编程方式评估PEP-508样式的平台标记,例如platform_system == 'Windows'。实现解析器并不是一件非常困难的事情,但是我认为pip中有一个。它叫什么?如何在自己的脚本中导入和使用它?

1 个答案:

答案 0 :(得分:2)

pkg_resources

pkg_resourcessetuptools软件包的一部分)提供了标记评估功能。

In [1]: from pkg_resources import evaluate_marker

In [2]: evaluate_marker('sys_platform == "darwin"')
Out[2]: True

In [3]: evaluate_marker('python_version > "3.7"')
Out[3]: False

In [4]: evaluate_marker('implementation_name == "cpython"')
Out[4]: True

In [5]: evaluate_marker('garbage')
Traceback (most recent call last):

  File "/Users/hoefling/Library/Python/3.7/lib/python/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-2-69434540d2ec>", line 1, in <module>
    evaluate_marker('garbage')

  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pkg_resources/__init__.py", line 1372, in evaluate_marker
    raise SyntaxError(e)

  File "<string>", line unknown
SyntaxError: Invalid marker: 'garbage', parse error at 'garbage'

packaging

在后台,pkg_resources.evaluate_marker使用packaging.markers.Marker.evaluate包中的packaging,因此您可以改用它:

In [6]: from packaging.markers import Marker

In [7]: Marker('"linux" in sys_platform').evaluate()
Out[7]: False