It's possible to use strings instead of port indices to select midi ports by name, this should be more reliable:
input
/output
can be port numbers or strings (as reported by thelist
action). If a string is specified, the first port whose name contains the string will be used (comparison is case-insensitive).