【问题标题】:How can I pass the result of a python script to the command line?如何将 python 脚本的结果传递到命令行?
【发布时间】:2020-09-27 17:40:51
【问题描述】:

我编写了一个 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])

【问题讨论】:

  • subprocess.call 是否应该在 for 循环中?
  • 尝试了任何一种方式。 aria2c 开始时好像要下载但没有下载一个字节。这就是为什么如果可能的话,我宁愿将它传递到终端窗口。

标签: python python-3.x linux subprocess


【解决方案1】:

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

您可以使用 shell 轻松获取 single 输出,尽管我不确定这是否能满足您的需求。在 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(Linux 下可能是. test_181_cli.sh

然后运行它:

(venv38) myuser@explore$ runmystuff

ariac b:
(venv38) myuser@explore$ runmystuff

ariac c:

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

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

【讨论】:

    【解决方案2】:

    您可以尝试以下步骤:

    1. 在同一文件夹中打开命令提示符

    2. 输入python file_name

    3. 你的程序的输出出现了。

    【讨论】:

    • 您的答案没有解决问题,即捕获 Python 脚本的输出并将其传递给另一个(外部)程序。按照您的步骤,只允许以常规方式运行 python 脚本。
    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2018-10-16
    • 2020-05-18
    相关资源
    最近更新 更多