Updating version numbers for Python Packages in Azure DevOps

Updating version numbers for Python Packages in Azure DevOps

So I did a previous post on how to create package libraries in Python, and I wanted to put in a post here on how to solve a problem I immediately identified.

If you look at the setup.py, you will see that the version number, and other details are very much hard coded into the file. This is concerning as it requires a manual step to go and update this before you can do a build / publish activity. And honestly, nowadays CI/CD is the way of the word.

So to resolve this, I built a script to have the automated build agent inject the version number created by the CI/CD tool. And that code is the following:

import fileinput
import sys

filename = sys.argv[1]
text_to_search = sys.argv[2]
replacement_text = sys.argv[3]
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

I then updated my setup.py with the following:

    python_requires = '>=3.7',

And that’s it, from their you just trigger this tile and inject the new build number into the file.

5 thoughts on “Updating version numbers for Python Packages in Azure DevOps

  1. Hello,

    Please share me an example for above.

    Also please let me know where I need to inject the script provided above.


    1. The setup.py file is used as part of creating the package, and I have more information here, and the python script just involves calling your python script as a step in a yaml task. See documentation here.

  2. Hi there, I am trying to replicate this set up. However, when I run the python code I get the response:
    filename = sys.argv[1]
    IndexError: list index out of range

    What exactly is sys.argv[1] expected to look like?

    Thanks for your blog, really appreciate it!

    1. The three arguments you are passing when you run the script are 1.) Path of the file, 2.) What token to look for, 3.) what to replace it with.

      1. I think what people are looking for is what the YAML looks like. Like, it seems like this will overwrite the tokens in the file with the buildNumber. But then on a subsequent build, the token will have already been replaced, so then what?

Leave a Reply

Your email address will not be published.