The Tails firewall will prevent you from doing this. Only applications that have been explicitly whitelisted are allowed to communicate with the outside world. This is by design.
Have a read of the Network Filter page on the Tails site.
You'll have to whitelist your application/script to allow it to connect to a foreign IP address. To do this you'll need to edit the file
/etc/ferm/ferm.conf. The file should be commented well enough to allow you to work out the config you'll need to add. (In theory... )
In the OnionShare code mentioned by the OP, they're effectively doing the same thing using a different method.
ferm is a tool that allows firewall rules to be written and stored in a separate config file.
If you look at the contents of a ferm file, you'll see the syntax is a simplified version of the options you would pass to the
iptables command, which is what they use in the OnionShare code.
For details on how an
iptables command translates to a ferm statement, see here.
iptables isn't available to the
amnesia user, which is why their script has to be run as root. (There are probably other reasons, too.)
Their code simply spawns
iptables as a separate process. For something more Pythonic, you could have a look at the
python-iptables package. (Note, I haven't used this myself. You'd have to ensure the code in this package is "safe" from the perspective on anonimity... )
Finally, opening holes in firewalls is dangerous. You'd have to ensure these holes couldn't be accidentally left open if, for example, your script died unexpectedly. (So if your script did spawn a separate child process, like the OnionShare code does, you would need to ensure that that child dies with its parent. The OnionShare code doesn't seem to do this - if the main script dies after line 238 but before 267, the firewall is left open. To protect against this you'd want the kernel to kill the child, as described in this thread.)