Typing stubs for pycurl
types-pycurl provides static type annotations (stubs) for the pycurl library, enabling static type checkers like MyPy and PyRight to analyze code that uses pycurl for network operations. It is part of the typeshed project, which centrally maintains type stubs for Python's standard library and many third-party packages. This package is automatically released, typically on a daily basis, to ensure compatibility with the corresponding pycurl runtime versions.
Warnings
- gotcha PycURL expects byte strings for non-ASCII data in many options (e.g., URL, POSTFIELDS). Passing Unicode strings with non-ASCII characters directly can lead to `UnicodeEncodeError` or `pycurl.error` (e.g., 'read function error/data error') if PycURL cannot encode them to ASCII.
- gotcha When `pycurl` encounters an error from the underlying `libcurl` library, it raises `pycurl.error`. The exception message may contain a numeric error code from `libcurl` (e.g., `(1, '')` for `CURLE_UNSUPPORTED_PROTOCOL`). The generic message might not immediately indicate the root cause.
- gotcha Passing an argument of an incorrect type to `c.setopt()` (e.g., an integer where a string is expected) will raise a `TypeError: invalid arguments to setopt`. Carefully check the `libcurl` documentation for the expected argument type of each option.
- breaking The `DEBUGFUNCTION` callback on Python 3 changed to take `bytes` rather than (Unicode) `str` as its argument. Code expecting `str` will need to decode the input.
- gotcha On Windows, an `ImportError` related to `libcurl` or `OpenSSL` can occur if the compile-time and runtime SSL backends do not match, or if `OpenSSL` headers are missing.
Install
-
pip install pycurl types-pycurl
Imports
- Curl
import pycurl from io import BytesIO c = pycurl.Curl()
- pycurl.error
import pycurl try: # pycurl operations pass except pycurl.error as e: print(f"PycURL error: {e}")
Quickstart
import pycurl
from io import BytesIO
import certifi
import os
buffer = BytesIO()
c = pycurl.Curl()
# Set the URL and write data to the buffer
c.setopt(pycurl.URL, 'https://example.com')
c.setopt(pycurl.WRITEDATA, buffer)
# Configure SSL certificates using certifi for secure connections
# (optional, but recommended for HTTPS)
if os.environ.get('PYCURL_CA_BUNDLE_PATH'):
c.setopt(pycurl.CAINFO, os.environ.get('PYCURL_CA_BUNDLE_PATH'))
elif os.path.exists(certifi.where()):
c.setopt(pycurl.CAINFO, certifi.where())
try:
c.perform()
body = buffer.getvalue().decode('utf-8')
print(f"HTTP Status Code: {c.getinfo(pycurl.HTTP_CODE)}")
print(f"Response body length: {len(body)} characters")
# print(body[:500]) # Print first 500 characters of the body
except pycurl.error as e:
# Troubleshooting tip: Enable verbose logging for more details
# c.setopt(pycurl.VERBOSE, True)
print(f"An error occurred: {e}")
finally:
c.close()