使用python在Ubuntu上打开磁铁链接



我有一个来自torrent网站的磁铁链接,它应该打开这个名为transmission的程序。如何用Python打开它?

我在ubuntu btw。我听说这个叫xdg-open的东西可以做到这一点,但我该如何使用它来打开磁铁链接?

如果这不是我想要的代码,我应该用什么来运行磁链接?

查看transmission-gtk的命令行参数有助于:

$transmission gtk--帮助

用法:transmission gtk〔OPTION…〕〔torrent files or urls〕

python解决方案的一种快速而肮脏的方法是使用os模块:

import os
os.system("transmission-gtk urlhere")

对外部程序进行此类调用的一种更好、更复杂的方法是使用subprocess模块。在python下可以找到更多的例子-如何创建子流程?。

xdg-open的工作原理基本相同。但是,它没有直接调用传输客户端,而是选择首选的Torrent应用程序(在这种情况下,首选是指默认应用程序,可以使用Ubuntu系统设置中的默认应用程序菜单进行设置)。通过从命令行调用程序,反复指向您提供的帮助文本,检查xdg-open:的退出代码可能会很有趣

$xdg打开-手动

1命令行语法错误。

2在命令行上传递的某个文件不存在。

3找不到所需的工具。

4操作失败。

下面的代码总结了在所有操作系统上下载的方法

  import subprocess , os , sys
  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)

最新更新