PycURL - A Python Interface To The cURL library
PycURL is a Python interface to the `libcurl` library, providing fast and feature-rich capabilities for network operations. It supports numerous protocols including HTTP, HTTPS, FTP, and more, exposing most of `libcurl`'s functionality like SSL, authentication, and proxy options. PycURL is often chosen for performance-critical applications and I/O multiplexing due to its speed. The current version is 7.45.7, with releases occurring periodically to incorporate `libcurl` updates and security fixes.
Warnings
- gotcha PycURL is a wrapper around `libcurl`, a system library. Installing PycURL via pip often requires `libcurl` and its development headers (e.g., `libcurl4-openssl-dev` on Debian/Ubuntu, `curl` on macOS via Homebrew) to be present on your system. Without these, installation may fail or lead to runtime errors, especially when building from source.
- gotcha SSL backend mismatches can cause runtime `ImportError` (e.g., `pycurl: libcurl link-time ssl backend (...) is different from compile-time ssl backend (...)`). This occurs if PycURL is built against a different SSL library than what `libcurl` uses at runtime.
- gotcha PycURL returns all network data as `bytes` objects. For text content, you must explicitly decode these `bytes` to `str` (e.g., using `.decode('utf-8')`). Conversely, when passing non-ASCII Unicode strings to `setopt` or `READFUNCTION`, they must first be encoded into `bytes` to avoid `UnicodeEncodeError` or `pycurl.error` (e.g., 'read function error/data error').
- deprecated While `c.setopt(c.WRITEFUNCTION, buffer.write)` still works, as of PycURL 7.19.3, `c.setopt(c.WRITEDATA, buffer)` is generally preferred and simpler as it accepts any Python object with a `write` method (like `io.BytesIO`).
- breaking The `DEBUGFUNCTION` callback on Python 3 now expects its argument to be `bytes` instead of a (Unicode) `string`.
- breaking The `CURLMOPT_*` option constants, related to the multi interface, were moved from the `Easy` class to the `Multi` class. They remain available in the top-level `pycurl` module for backward compatibility.
Install
-
pip install pycurl -
sudo apt-get install libcurl4-openssl-dev python3-pycurl -
brew install curl
Imports
- pycurl
import pycurl
- Curl
import pycurl c = pycurl.Curl()
- BytesIO
from io import BytesIO
Quickstart
import pycurl
from io import BytesIO
def fetch_url(url):
buffer = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEDATA, buffer)
# Optional: For HTTPS, use certifi for certificate bundle
# import certifi
# c.setopt(c.CAINFO, certifi.where())
try:
c.perform()
status_code = c.getinfo(pycurl.RESPONSE_CODE)
response_body = buffer.getvalue().decode('utf-8', errors='ignore')
print(f"Status Code: {status_code}")
print(f"Response Body (first 200 chars):\n{response_body[:200]}")
except pycurl.error as e:
print(f"PycURL error: {e}")
finally:
c.close()
# Example usage
fetch_url('https://httpbin.org/get')