Python SDK Pythonbeta

Installation

The Blackfire Python SDK is available with the Blackfire Python Package.

Blackfire Python SDK

The Blackfire Python SDK allows you to generate profiles from your own code and eases the integration with third-party libraries.

The main entry point of the SDK is the blackfire module:

1
from blackfire import probe

The probe allows you to profile any parts of your code:

1
2
3
4
5
6
7
8
from blackfire import probe

probe.initialize()
probe.enable()

# some Python code you want to profile

probe.end()

Manually Configuring the Blackfire Probe

The Blackfire Probe is usually configured by environment variables, but you can customize this when calling the initialize() method.

The initialize() method takes optional parameters that allow you to configure the Blackfire Probe:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
probe.initialize(
    query=None,
    client_id=None,
    client_token=None,
    agent_socket=None,
    agent_timeout=None,
    endpoint=None,
    log_file=None,
    log_level=None,
    config_file='~/.blackfire.ini'
)

Instrumenting Code by Wrapping Execution

The SDK provides the run(call_end=True) method that simplifies the use of the enable() and disable() methods:

1
2
3
4
5
from blackfire import probe

with probe.run():
    foo()
    bar()

is equivalent to:

1
2
3
4
5
6
7
8
9
from blackfire import probe

probe.enable()
try:
    foo()
    bar()
finally:
    probe.disable()
    probe.end() # if call_end is True.

Controlling Automatic Instrumentation

1
2
3
from blackfire import probe

probe.initialize()

Start profiling the code by calling enable():

1
2
# Start the profiling
probe.enable()

Stop profiling the code by calling disable():

1
2
# Stop the profiling
probe.disable()

You can call enable() and disable() as many times as needed in your code. You can also discard any collected data by calling clear_traces().

Calling end() instead of disable() stops the profiling and forces the collected data to be sent to Blackfire:

1
2
3
# Stop the profiling
# Send the result to blackfire
probe.end()