【问题标题】:wget missing url with shlex and subprocesswget缺少带有shlex和子进程的url
【发布时间】:2021-03-12 07:48:56
【问题描述】:

我很难理解为什么这会失败并出现wget: missing URL 错误:

import shlex
import subprocess

copy_command = "wget -O - 'http://example.com/somepath/somefile.txt?someparam=test' | sshpass -p pass ssh user@localhost -p 2222 \"cat - > /upload/somefile.txt\""

cmd = shlex.split(copy_command, posix=False)

with subprocess.Popen(
    cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True
) as proc:
    output, error = proc.communicate()

我在这里缺少什么?如果我只是直接给子进程copy_command 字符串,那么它可以正常工作。

【问题讨论】:

  • 等等,你不能通过一次调用 Popen 来模拟整个管道的重定向。您需要多次调用,每个进程调用一次。
  • 感谢您的评论!请注意,当我不使用 shlex 时,这可以正常工作。
  • 因为shell=True 将它作为字符串传递给带有sh -c '...' 的shell。所以子shell然后解释管道。
  • 顺便说一句,我不太确定你想在那里做什么,但我相信有更好的方法。
  • 假设您使用的是 Linux。

标签: python subprocess wget shlex


【解决方案1】:

要设置管道,需要父进程生成所有涉及的程序,并将彼此的 stdio 连接(管道)。

subprocess 的 Python 文档解释了如何执行此操作。

它适用于字符串参数和shell=True,因为它只是将命令行交给子 shell,而该 shell 处理所有这些细节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多