partx and kpartx have very similar functionality, just different output.
It looks like you're currently using kpartx to tell the kernel to add
and delete partition devices; you're also parsing the output to see what
device was created.
kpartx output looks like this:
add map loop0p1 (254:1): 0 10483679 linear 7:0 2048
And you're using the third word as the device name.
partx (with the -v option) writes output like this:
partition: none, disk: debian.img, lower: 0, upper: 0
Trying to use '/dev/loop0' for the loop device
/dev/loop0: partition table type 'gpt' detected
range recount: max partno=1, lower=0, upper=0
/dev/loop0: partition #1 added
That's not quite as trivial to parse, but you could look for lines that
match `^\(/dev/[^:]*\): partition #\([0-9]*\) added$`, and construct the
device name as match 1 + "p" + match 2.