Skip to content

Python

Elegant Env Vars for Jenkins Python

In my case, I use Jenkins to drive some Python scripts. We can set configuration in Jenkins via System Properties, Node Configuration or Build Parameters.

We can get the configurations through environment variables, and also pass stage outputs to other stages via environment variables.

Visualizing and retaining environment variables is crucial, So I want to manage environment variables in an elegant way.

I implemented a class EnvSettings extend from pydantic.BaseSettings to manage environment variables:

Subclassing of pathlib.Path

In my case, I wanted to enhance the functionality of pathlib.Path to include additional methods for file or directory operations specific to my project.

For example, I wanted to add a method that would allow me to easily zip a directory or a file directly from the Path object:

from pathlib import Path

class EnhancePath(Path):
    def zip(self):
        print('zip file')

EnhancePath.cwd()

This code works normally on python 3.13, but it raises an error on python 3.11 and below (I don't test on 3.12):

AttributeError: type object 'EnhancePath' has no attribute '_flavour'

Stop or Kill a Thread

It is generally a bad pattern to kill a thread abruptly, in Python, and in any language.

The nice way of handling this, if you are managing your own thread, is to have an exit flag that each thread checks on a regular interval to see if it is time to exit:

Source Code Batch Changes

Sometimes, existing code needs to be modified in batches, and these operations are too complex to be achieved through the IDE's replacement function.

AST is a good choice to do that.