gpt4 book ai didi

python - pycurl 取消传输并尝试 & except

转载 作者:行者123 更新时间:2023-12-01 00:01:05 33 4
gpt4 key购买 nike

如何在 pycurl 中取消传输?我曾经在 libcurl 中返回 -1 但 pycurl 似乎不喜欢那样(“pycurl.error:写入回调 -1 17 的返回值无效”)返回 0 也不起作用,我得到“错误:(23,'写入主体失败')”。另外我如何使用 pycurl 进行尝试/除外?我没有看到任何在线示例,也没有看到网站上的 pycurl 示例

最佳答案

示例代码在这里会有帮助。从错误消息来看,并在源代码中查找它,您已经设置了一个写入回调。我认为这是由 CURLOPT_WRITEFUNCTION 配置的,其文档如下:

Return the number of bytes actually taken care of. If that amount differs from the amount passed to your function, it'll signal an error to the library and it will abort the transfer and return CURLE_WRITE_ERROR.

pycurl 包装器代码检查该值是否在 0 和传递给它的数字之间。这就是为什么 -1 失败,以及为什么 0 触发 CURLE_WRITE_ERROR,引发“写入正文失败”异常。 pycurl 代码是:

 /* run callback */
arglist = Py_BuildValue("(s#)", ptr, total_size);
if (arglist == NULL)
goto verbose_error;
result = PyEval_CallObject(cb, arglist);
Py_DECREF(arglist);
if (result == NULL)
goto verbose_error;

/* handle result */
if (result == Py_None) {
ret = total_size; /* None means success */
}
else if (PyInt_Check(result)) {
long obj_size = PyInt_AsLong(result);
if (obj_size < 0 || obj_size > total_size) {
PyErr_Format(ErrorObject, "invalid return value for write callback %ld %ld", (long)obj_size, (long)total_size);
goto verbose_error;
}
ret = (size_t) obj_size; /* success */
}
else if (PyLong_Check(result)) {
... identical code for Long ...
}
else {
PyErr_SetString(ErrorObject, "write callback must return int or None");
goto verbose_error;
}

我在 pycurl 中没有看到该函数有任何方法支持另一个返回值。可能还有其他方法,例如设置进度回调,这似乎允许中止。

curl本身的相关代码是:

/* If the previous block of data ended with CR and this block of data is
just a NL, then the length might be zero */
if(len) {
wrote = data->set.fwrite_func(ptr, 1, len, data->set.out);
}
else {
wrote = len;
}

if(CURL_WRITEFUNC_PAUSE == wrote)
return pausewrite(data, type, ptr, len);

if(wrote != len) {
failf(data, "Failed writing body (%d != %d)", (int)wrote, (int)len);
return CURLE_WRITE_ERROR;
}

所以你可以看到pycurl不支持返回curl本身允许的CURL_WRITEFUNC_PAUSE。还可以看到curl没有办法通过write回调函数支持中止。您将不得不使用其他东西。

关于python - pycurl 取消传输并尝试 & except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/526325/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com