在 Ubuntu 上使用 python 打开磁力链接
-
09-12-2019 - |
题
我有一个来自 torrent 站点的磁力链接,应该可以打开这个名为 Transmission 的程序。我如何使用 Python 打开它?
顺便说一句,我在 ubuntu 上。我听说这个东西叫 xdg-open
可以做到这一点,但我如何使用它来打开磁力链接?
如果这不是我正在寻找的代码,我应该使用什么来运行磁力链接?
解决方案
看一下命令行参数 transmission-gtk
帮助:
$ Transmission-gtk --help
用法:Transmission-gtk [选项...] [torrent 文件或 url]
python 解决方案的一种快速而肮脏的方法是使用 os
模块:
import os
os.system("transmission-gtk urlhere")
对外部程序进行此类调用的一种更好、更复杂的方法是使用 subprocess
模块。更多示例可以在下面找到 python - 如何创建子进程?.
xdg-open
工作方式几乎相同。但它不是直接调用传输客户端,而是选择首选的 Torrent 应用程序(本例中的首选表示默认应用程序,可以使用 Ubuntu 系统设置中的默认应用程序菜单进行设置)。反复向您指出通过从命令行调用程序给出的帮助文本,检查退出代码可能会很有趣 xdg-open
:
$ xdg-open --手册
...
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)
.
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)
不隶属于 StackOverflow