从导入变量设置.py从外部票据

2024-05-20 17:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个设置.py像这样的文件(不是在pwd中,不是在Python path中,在某个地方是一个随机文件):

import ext_modules

config = {
    'name': 'mesos.executor',
    'version': '1.4.1',
    'description': 'Mesos native executor driver implementation',
    'author': 'Apache Mesos',
    'author_email': 'dev@mesos.apache.org',
    'url': 'http://pypi.python.org/pypi/mesos.executor',
    'namespace_packages': [ 'mesos' ],
    'packages': [ 'mesos', 'mesos.executor' ],
    'package_dir': { '': 'src' },
    'install_requires': [ 'mesos.interface == 1.4.1' ],
    'license': 'Apache 2.0',
    'keywords': 'mesos',
    'classifiers': [ ],
    'ext_modules': [ ext_modules.executor_module ]
}

from setuptools import setup
setup(**config)

我想从一个外部(Python)脚本导入config[“install峎requires”]。我正在寻找最简单的方法来实现这一点,因为它打算从其他脚本运行,甚至可能不是Python。在

一个Python的一行代码会很棒。在


Tags: install文件orgimportpypimodulesconfigpackages
2条回答

在文档中:https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly

在您的情况下:

import importlib
setup_file = "path/to/setup.py"
spec = importlib.util.spec_from_file_location("setup", setup_file)
setup = importlib.util.module_from_spec(spec)
spec.loader.exec_module(setup)
# And now access it
print(setup.config["install_requires"])

为了避免从python导入任意路径,还需要从一个模块导入一个

import ast, _ast

def filter_setup_st(node):
    if isinstance(node, _ast.Expr) and isinstance(node.value, _ast.Call):
        if node.value.func.id == 'setup':
            return False
    return True

with open('/path/to/example_setup.py') as f:
    c = f.read()   
tree = ast.parse(c)
tree.body = [n for n in tree.body if filter_setup_st(n)]

ns = {}
exec(compile(tree, '__string__', 'exec'), {}, ns)

assert ns['config']['install_requires'] == ['mesos.interface == 1.4.1']

另一种方法有点棘手,暂时使setuptools.setup无效:

^{pr2}$

更新:

如果您还想要bypass importext_modules

import sys

class fake_ext_module():

    executor_module = 'spam'

sys.modules['ext_modules'] = fake_ext_module

相关问题 更多 >