How can I get the version defined in setup.py (setuptools) in my package?

前端 未结 16 809
无人及你
无人及你 2020-11-27 09:47

How could I get the version defined in setup.py from my package (for --version, or other purposes)?

16条回答
  •  孤独总比滥情好
    2020-11-27 10:42

    I wasn't happy with these answers... didn't want to require setuptools, nor make a whole separate module for a single variable, so I came up with these.

    For when you are sure the main module is in pep8 style and will stay that way:

    version = '0.30.unknown'
    with file('mypkg/mymod.py') as f:
        for line in f:
            if line.startswith('__version__'):
                _, _, version = line.replace("'", '').split()
                break
    

    If you'd like to be extra careful and use a real parser:

    import ast
    version = '0.30.unknown2'
    with file('mypkg/mymod.py') as f:
        for line in f:
            if line.startswith('__version__'):
                version = ast.parse(line).body[0].value.s
                break
    

    setup.py is somewhat of a throwaway module so not an issue if it is a bit ugly.


    Update: funny enough I've moved away from this in recent years and started using a separate file in the package called meta.py. I put lots of meta data in there that I might want to change frequently. So, not just for one value.

提交回复
热议问题