python - 从子进程执行 curl 的正确方法是什么?

标签 python curl subprocess

我试图从 subprocess 调用 curl 来下载图像,但一直收到 curl 错误(错误代码 2 ..which from doc 指的是 CURL_FAILED_INIT)。我没有使用 urllib,因为我最终将使用 subprocess 执行脚本。以下是代码片段

import subprocess
import multiprocessing

def worker(fname, k):
    f = open(fname, 'r')
    i = 0
    for imgurl in f:
        try:
            op = subprocess.call(['curl', '-O', imgurl], shell=False)
        except:
            print 'problem downloading image - ', imgurl

def main():
    flist = []
    flist.append(sys.argv[1])
    flist.append(sys.argv[2])
    ...

    for k in range(1):
        p = multiprocessing.Process(target=worker, args=(flist[k],k))
        p.start()

O/P:

curl: try 'curl --help' or 'curl --manual' for more information

2

curl: try 'curl --help' or 'curl --manual' for more information

2

....

最佳答案

如果你想运行一个 shell 命令,subprocess 是最好的选择。因为这可以在它自己的进程中启动一个 shell 命令,所以使用 multiprocessing 充其量是多余的。当你想在不同的进程中运行你的 python 程序的一个函数时,多处理就派上用场了。您似乎打算运行 shell 命令,而不是 python 函数。

我不熟悉curl。如果您的目的是从 curl 获取标准输出,请使用 subprocess.Popen()subprocess.call() 返回程序返回码,而不是 stdout

参见 http://docs.python.org/release/3.2/library/subprocess.html

类似于:

subp = subprocess.Popen(['curl', '-O', imgurl], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

curlstdout, curlstderr = subp.communicate()

op = str(curlstdout)

可能会更近一些。正如我所说,不熟悉 curl,因此您的程序可能会有所不同。

关于python - 从子进程执行 curl 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231362/

相关文章:

python - 页面的链接和该子页面的链接。递归/线程

php - 使用 CURL 将 http 请求发送到本地文件

linux - 如何使用 curl 命令调用具有 getopts 的 bash 脚本?

python - 装饰\委托(delegate)一个文件对象来添加功能

python - 如何运行使用 subprocess.call 的同一 Python 脚本的多个实例

python - 如何在 Python 子进程中模拟按键?

python - 寻找最大的重复子串

python - 如何猜测图像 mime 类型?

python - 尝试使用flask-security注册用户时出现"TypeError: hashpw() argument 1 must be str, not bytes"

rest - AFNetworking 结果与 CURL 不同