首页 > 解决方案 > 如何将 python 脚本的结果传递到命令行?

问题描述

我编写了一个 Python 脚本,用于收集我要下载的种子的磁力链接。

然后如何在命令行中将其传递给 aria2c。

这是我到目前为止所尝试的,aria2c 开始时好像它会下载但它不会下载单个字节。我是一个完全的菜鸟,所以我很抱歉,并非常感谢你的帮助。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from pyYify import yify
import os
import subprocess
driver = webdriver.Chrome()

driver.get('https://mypiratebay.net/')
searchbox = driver.find_element_by_xpath('//*[@id="home"]/main/section/form/div[1]/input')
searchbox.send_keys('Toy Story 4')
searchbox.send_keys(Keys.RETURN)
torrentlink = driver.find_element_by_xpath('//*[@id="st"]/span[2]/a')
time.sleep(3)
torrentlink.click()

for a in driver.find_elements_by_xpath('//*[@id="d"]/a'):
    magnetlink = (a.get_attribute('href'))
    magnetlink = str(magnetlink)

subprocess.call(['aria2c', magnetlink])

标签: pythonpython-3.xlinuxsubprocess

解决方案


要回答您提出的问题,至少部分:

您可以使用 shell 轻松获取单个输出,尽管我不确定这对您的需求有多好。在 macOS 上,使用 bash:

test_181_cli.py:

import random
print (random.choice(["a","b","c"]))

test_181_cli.sh

runmystuff(){
    url=$(python test_181_cli.py)
    printf "\nariac $url:"

    #what you actually want
    #ariac $url
}

那么你需要加载你的 bash 函数定义:

source test_181_cli.sh(可能是. test_181_cli.sh在 Linux 下)

然后运行它:

(venv38) myuser@explore$ runmystuff

ariac b:
(venv38) myuser@explore$ runmystuff

ariac c:

现在,就 ariac 实际上不工作而言,我怀疑将它传递给命令行会改善子进程的情况,并且处理多个 url 无论如何都会更难。

我建议您打印print(f":{magnetlink}:")注意故意冒号 - 检查是否没有多余的空格并适当地格式化。然后尝试aria2c <your url>手动运行。你可能有各种各样的其他问题和子进程,一旦你有一个正确的命令行,可能不是它们的原因。此外,Daniel Walker 的评论很到位:您的子流程调用属于循环。


推荐阅读