用python打开Ubuntu上的磁铁链接

2024-06-01 02:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个磁铁链接从一个torrent网站,应该打开这个程序名为传输。怎么我要用Python打开它吗?在

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

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


Tags: 代码程序网站链接ubuntuopentorrent磁铁
2条回答

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

  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)

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

$ transmission-gtk help

Usage: transmission-gtk [OPTION...] [torrent files or urls]

python解决方案的一个快速而肮脏的方法是使用^{}模块:

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

对外部程序进行此类调用的一种更好、更复杂的方法是使用^{}模块。在python - how to create a subprocess?下可以找到更多的例子。在

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

$ xdg-open manual

...

1 Error in command line syntax.

2 One of the files passed on the command line did not exist.

3 A required tool could not be found.

4 The action failed.

相关问题 更多 >