Skip to main content
 首页 » 编程设计

python之通过 Python 替换文件中的更新版本字符串

2024年11月24日21thcjp

我想用 Python 替换 foopkg/__init__.py 中的版本字符串:

__version__ = "0.1.3" 

… 并在 setup.py 中:

#!/usr/bin/env python 
from os.path import join 
from setuptools import find_packages, setup 
 
 
version = "0.1.3" 
 
entry_points = { 
    "console_scripts": [ 
        "say-foo = fooproj.foo:foo" 
    ] 
} 
 
[...] 

这两个文件的绝对路径和新版本号分别通过 file_path 和 new_version 参数传递给以下函数:

def update_version_strings(file_path, new_version): 
    VERSION_REGEX = re.compile( 
        r"(^(__)?version(__)?\s*=\s*\")(?P<version>\d+\.\d+\.\d+)\"$" 
    ) 
    with open(file_path, "r+") as f: 
        content = f.read() 
        f.seek(0) 
        f.write( 
            re.sub( 
                VERSION_REGEX, 
                lambda match: '{}{}"'.format(match.group(1), new_version), 
                content, 
            ) 
        ) 
        f.truncate() 

通过以下方式调用此函数:

update_version_strings("/path/to/foopkg/__init__.py", "0.1.4") 

... 正确地将 foopkg/__init__.py 中的版本号行替换为 __version__ = "0.1.4",但是 update_version_strings("/path/to/setup.py", "0.1.4") 不会对 setup.py 文件产生任何更改。

我想错误在于 VERSION_REGEX 和 lambda match 指令的某种组合。诚然,我并不精通正则表达式,而且几乎可以肯定,我是以一种不太理想的方式来做这件事的。

替换这两种不同版本字符串格式并将更改写入相应文件的最佳方法是什么?

加分项:最好也支持单引号样式,例如 __version__ = '0.1.3' 和 version 中的版本号= '0.1.3' 字符串也将被正确替换。 (^_^)

请您参考如下方法:

对两种不同的版本字符串格式使用以下方法(它还包括单引号/双引号):

def update_version_strings(file_path, new_version): 
    version_regex = re.compile(r"(^_*?version_*?\s*=\s*['\"])(\d+\.\d+\.\d+)") 
    with open(file_path, "r+") as f: 
        content = f.read() 
        f.seek(0) 
        f.write( 
            re.sub( 
                version_regex, 
                lambda match: '{}{}'.format(match.group(1), new_version), 
                content, 
            ) 
        ) 
        f.truncate()