Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: Opening A Magnet Link Contained In A Variable

I have a magnet link (e.g.: magnet:?xt=urn:btih:1c1b9f5a3b6f19d8dbcbab5d5a43a6585e4a7db6) contained in a variable as a string and would like the script to open the default program that handles magnet links so that it starts downloading the torrent (like if I opened a magnet link from within my file manager).

For the sake of making answers clear we will say that we have the magnet link in a variable called magnet_link.

like image 824
Eden Crow Avatar asked Feb 19 '12 16:02

Eden Crow


2 Answers

Here is a small code snippet that sums up the method on all the operating systems

  import sys , subprocess
  def open_magnet(magnet):
        """Open magnet according to os."""
        if sys.platform.startswith('linux'):
            subprocess.Popen(['xdg-open', magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        elif sys.platform.startswith('win32'):
            os.startfile(magnet)
        elif sys.platform.startswith('cygwin'):
            os.startfile(magnet)
        elif sys.platform.startswith('darwin'):
            subprocess.Popen(['open', magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            subprocess.Popen(['xdg-open', magnet],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
like image 24
Natesh bhat Avatar answered Sep 19 '22 23:09

Natesh bhat


On Windows you can use os.startfile:

os.startfile(magnet_link)

For Mac/OSX you could probably use applescript and pipe it to osascript, for Linux you might be able to use xdg-open.

like image 50
zeekay Avatar answered Sep 18 '22 23:09

zeekay