I found two implementations.

One

import socket
socket.gethostbyname(socket.gethostname())

Two: recommend!

This way will create a new UDP package and adding local IP address in it.

It will not actually send the package。

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()

Reference