### View all instances of class A Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Example command to view all instances of class A in the __main__ module. ```shell # View all instances of class A vmtool -a getInstances -c __main__ A ``` -------------------------------- ### module command examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows output for an existing module (__main__.py) and for a file not imported into the process. ```shell # Corresponding module is __main__.py module ~/tt_main.py # Not imported into the specified process module ~/not_exist.py ``` -------------------------------- ### getglobal usage examples for module variables and class static variables Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Example commands for observing variables in Python files started by __main__. The first observes a module variable, the second observes a class static variable. ```shell # Module variables getglobal __main__ g_list ``` ```shell # Class static variables getglobal __main__ classA static_field ``` -------------------------------- ### torch profile example: sample hello method Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Samples the hello method of class A in the __main__ module. The generated trace.json file must be opened in chrome://tracing/ for visualization. ```shell # Sample the hello method of class A in the __main__ module torch profile __main__ A hello ``` -------------------------------- ### torch memory examples: snapshot and record Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Two command examples: one snapshots the torch memory used by the current process, the other records memory allocation actions during method execution. The generated snapshot.pickle file must be analyzed in https://pytorch.org/memory_viz. ```shell # Snapshot the torch memory used by the current process # Due to torch monitoring memory torch memory -s ``` ```shell # Observe memory allocation actions during method execution torch memory -r __main__ Solution call ``` -------------------------------- ### tt command usage examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Examples of using the tt command to record method calls, list records, display details, re-trigger calls, and filter by return value or argument. ```shell # Record module method tt -t __main__ func # Record class method tt -t __main__ A func # Display called method record list tt -l # Display specified call details tt -i 1000 -x 3 # Re-trigger the call with index 1000, using the same input tt -i 1000 -p # Only observe records with return value 'success' and time consumption greater than 10ms tt -t __main__ func -f "return_obj['success']==True and cost>10" # Only observe requests where the first method parameter contains a query field with value "hello" tt -t __main__ func -f "args[0][\"query\"]=='hello'" ``` -------------------------------- ### View help for a command Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Displays all available commands and their usage. Optionally, pass a command name to view its specific help. ```shell help [command] ``` -------------------------------- ### perf command examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows default usage, custom output path, and sampling for 30 seconds. Note: On macOS, root permissions are required for py-spy. ```shell perf # Output will be exported to ~/flamegraph.svg perf -f ~/flamegraph.svg # Sample for 30s perf -d 30 -f ~/flamegraph.svg ``` -------------------------------- ### Stack command usage examples (Linux) Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows common usages of the `stack` command: view Python thread stacks, view native stacks, and export stack information to a file. ```shell # View Python thread stacks stack # View native stacks of Python threads stack --native # Export execution stack information to a file stack -f ./stack.log ``` -------------------------------- ### reload usage examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home These commands reload the func method in the entry module, optionally under a class. ```shell # Reload the func method in the entry module reload __main__ func # Reload the func method under class classA in the entry module reload __main__ classA func ``` -------------------------------- ### watch command examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Examples of using the watch command to observe function calls with various filters and options. The -x option sets display depth, -f filters by expression, and --expr specifies the expression to observe. ```shell # watch module function watch __main__ func -x 2 ``` ```shell # watch module function and filter parameters watch __main__ func -f "args[0][\"query\"]=='hello'" ``` ```shell # watch module function and filter return values watch __main__ func -f "return_obj['success']==True" ``` ```shell # watch module function and filter function call time consumption watch __main__ func --expr "{return_obj,args}" -f "cost>10" ``` ```shell # watch class function watch __main__ classA func ``` -------------------------------- ### Start debugging with flight_profiler pid Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Starts debugging by passing the target process PID as a parameter. After execution, you can enter debugging commands. ```shell flight_profiler pid ``` -------------------------------- ### Enable Interactive Console Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Starts the interactive console in the specified process, allowing custom scripts and system property queries. ```shell console ``` -------------------------------- ### trace command examples Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Three example invocations of the trace command: tracing a module function, tracing with a 1ms interval filter, and tracing a class method. The -i option filters internal calls by execution time. ```shell # Trace module function trace __main__ func # Trace module function and only trace function calls with execution time exceeding 1ms trace __main__ func -i 1 # Trace class function trace __main__ classA func ``` -------------------------------- ### View variables of instances of class A Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Example command to view variables of instances of class A using the -e expression option. ```shell # View variables of instances of class A vmtool -a getInstances -c __main__ A -e instances[0].val ``` -------------------------------- ### getInstances command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Displays the command-line syntax for the vmtool getInstances action. Use it to view class instances in a Python process. ```shell vmtool -a getInstances -c module class [-e ] [-x ] [-n ] [-v] [-r] ``` -------------------------------- ### Server Plugin Example Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Develop a server plugin for command 'test'. Place it in src/python/plugins with name style server_plugin_test.py. Define get_instance returning a plugin instance that implements async do_action, outputting stream messages via asyncio.Queue. The example sends messages 1-5, with message 5 marked as end. ```python from asyncio import sleep from flight_profiler.plugins.server_plugin import Message, ServerPlugin, ServerQueue class TestServerPlugin(ServerPlugin): def __init__(self, cmd: str, out_q: ServerQueue): super().__init__(cmd, out_q) async def do_action(self, param): print("server plugin test do action") i = 0 while i < 5: i = i + 1 # stream message 1-5, message 5 marked as end await self.out_q.output_msg( Message(True if i == 5 else False, "message-" + str(i)) ) await sleep(1) def get_instance(cmd: str, out_q: ServerQueue): return TestServerPlugin(cmd, out_q) ``` -------------------------------- ### getInstances usage examples Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/WIKI.md Examples for viewing all instances of class A in __main__ and viewing instance variables using -e. ```shell # View all instances of class A vmtool -a getInstances -c __main__ A ``` ```shell # View variables of instances of class A vmtool -a getInstances -c __main__ A -e instances[0].val ``` -------------------------------- ### Find target process PID with ps Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Lists Python processes to identify the target debugging process PID before starting debugging. ```shell ps -ef | grep python ``` -------------------------------- ### getInstances Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Views class instances in the Python VM. It allows filtering, expanding, and controlling the display of instances. ```APIDOC ## getInstances ### Description Views class instances in the Python VM. It allows filtering, expanding, and controlling the display of instances. ### Command ```shell vmtool -a getInstances -c module class [-e ] [-x ] [-n ] [-v] [-r] ``` ### Parameters #### Required Parameters - **module** (string) - Required - Module where the class is located. Example: `__main__`, `my.pkg.modulename` - **class** (string) - Required - Class name. Example: `className` #### Optional Parameters - **-e, --expr ** (string) - Optional - Expression for observing objects, reference Python method parameters as (instances), instances is the instance list of the corresponding class, needs to return a right-value expression about instances. Example: `-e instances[0].fieldA` - **-x, --expand ** (integer) - Optional - expand, depth to display observed objects, defaults to 1, maximum is 4. Example: `-x 2` - **-r, --raw** (flag) - Optional - Whether to directly display the string representation of the target. Example: `-r` - **-v, --verbose** (flag) - Optional - Whether to display all sub-items of target lists/dictionaries. Example: `-v` - **-n, --limits ** (integer) - Optional - Control the number of displayed instances, defaults to 10, -1 means no limit. Example: `-n 1` ### Output Display For variables in python files started by __main__, use the following command: ```shell # View all instances of class A vmtool -a getInstances -c __main__ A # View variables of instances of class A vmtool -a getInstances -c __main__ A -e instances[0].val ``` ![img.png](https://raw.githubusercontent.com/alibaba/PyFlightProfiler/refs/heads/main/docs/images/vmtool.png) ``` -------------------------------- ### tt command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows the full command-line syntax for the tt command, including all optional parameters for observing method calls across time periods. ```shell tt [-t module [class] method] [-n ] [-l] [-i ] [-d ] [-da] [-x ] [-p] [-f ] [-r] [-v] [-m ] ``` -------------------------------- ### forceGc command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Displays the command-line syntax for the vmtool forceGc action. Use it to force garbage collection. ```shell vmtool -a forceGc ``` -------------------------------- ### Example 2: Standard library module Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-module/SKILL.md Example for a standard library module, e.g., json. Shows the command and its output. ```bash flight_profiler --cmd "module /Users/zy/miniforge3/envs/py39/lib/python3.9/json/__init__.py" --no-color ``` ```text json ``` -------------------------------- ### CLI Plugin Example Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Develop a CLI plugin for command 'test'. Place it in src/python/plugins with name style cli_plugin_test.py. Define get_instance returning a plugin instance that implements sync do_action, sending a request to the HTTP server and iterating stream messages to print to console. ```python from flight_profiler.plugins.cli_plugin import BaseCliPlugin from flight_profiler.utils.cli_util import common_plugin_execute_routine class TestCliPlugin(BaseCliPlugin): def __init__(self, port, server_pid): super().__init__(port, server_pid) def do_action(self, cmd): common_plugin_execute_routine( cmd="test", param=cmd, port=self.port, raw_text=True ) def on_interrupted(self): pass def get_instance(port: str, server_pid: int): return TestCliPlugin(port, server_pid) ``` -------------------------------- ### Check target Python environment and install flight_profiler Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-attach/SKILL.md Use these commands to locate the target process's Python executable, verify flight_profiler is installed in that environment, install it if needed, and run it with the same environment's binary. Replace with the actual process ID. ```bash # Step 1: Find the target process's Python executable ls -l /proc//exe # Linux ps -p -o command= # macOS # Step 2: Check if flight_profiler is already installed in that environment /path/to/target/python -m pip show flight_profiler # Step 3: If not installed, install it using the target's pip /path/to/target/python -m pip install flight_profiler # Step 4: Run flight_profiler using the same environment's binary /path/to/target/bin/flight_profiler ``` -------------------------------- ### Run Unit Tests Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Run all unit tests using the make test command. ```shell make test ``` -------------------------------- ### Correct import inside method body Source: https://github.com/alibaba/pyflightprofiler/wiki/Home This example works because the time module is imported inside the method body at runtime, which is allowed. ```python def func(): print(2) # ---------------- new added --------------------- # Work properly because `time` module is imported at runtime import time print(time.time()) # ------------------------------------------------ ``` -------------------------------- ### Enable memory history for torch 2.0.0 <= torch < 2.1.0 Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Add at program start to enable sampling of memory allocation history for torch versions 2.0.0 up to but not including 2.1.0. Then use the snapshot command to view. This allows tracing stack information for allocations from program startup. ```python from torch.cuda.memory import _record_memory_history _record_memory_history(enabled=True, trace_alloc_max_entries=100_000, trace_alloc_record_context=True) ``` -------------------------------- ### module command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Outputs the module name corresponding to a filename in the injected process. The filepath parameter is required. ```shell module filepath ``` -------------------------------- ### Example async stack output Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/WIKI.md Example output from the `stack -a` command showing an async coroutine/task stack with thread, task name, state, coroutine, and stack frames. ```text ============================================================ Async Coroutine/Task Stacks ============================================================ Thread: AsyncEventLoop (tid: 0x16f8a7000) -------------------------------------------------- Task #1: FetchAPI1 State: WAITING Coroutine: fetch_data_loop Stack (3 frames): File "/app/demo.py", line 95, in fetch_data_loop await fetch_data(name, delay) File "/app/demo.py", line 26, in fetch_data await asyncio.sleep(delay) File "/usr/lib/python3.9/asyncio/tasks.py", line 649, in sleep return await future ============================================================ ``` -------------------------------- ### Example 1: Main script file Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-module/SKILL.md The entry-point script is always __main__. This example shows the command and its output. ```bash flight_profiler --cmd "module /Users/zy/workspace/app/main_script.py" --no-color ``` ```text __main__ ``` -------------------------------- ### Analyze thread stacks with stack command (Mac) Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Views Python execution stack information for all threads in the process on Mac, with support for exporting to a file. ```shell stack [filepath] ``` -------------------------------- ### Install Poetry Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Install the Poetry dependency manager using pip3. The command output will indicate the PATH environment variable to add Poetry to. ```shell pip3 install poetry ``` -------------------------------- ### module subcommand usage and options Source: https://github.com/alibaba/pyflightprofiler/blob/main/README.md Shows the CLI usage, example, and options for the `module` subcommand, which determines the correct module name for a given source file path. Useful when you know the file location but are unsure how it was imported. ```text USAGE: module filepath EXAMPLES: module /home/admin/application/compute.py OPTIONS: Absolute or relative path to the Python source file. ``` -------------------------------- ### perf command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Samples the process to generate a flame graph. Options: -f for output path, -r for samples per second, -d for duration. Defaults: current directory flamegraph.svg, 100 samples/sec, wait for interruption. ```shell perf [pid] [-f ] [-r ] [-d ] ``` -------------------------------- ### trace command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows the full command-line syntax for the trace command. The module and method are required; class is optional. Options include -i, -nm, -et, -d, -n, and -f. ```shell trace module [class] method [-i ] [-nm ] [-et ] [-d ] [-n ] [-f ] ``` -------------------------------- ### Install AI Coding Agent Skills Source: https://github.com/alibaba/pyflightprofiler/blob/main/README.md One-command installation of AI coding agent skills for Claude Code, Gemini CLI, or Codex. Run this command to set up the skills for AI-assisted diagnostics. ```shell flight_profiler install-skills ``` -------------------------------- ### Install skills to a custom directory Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/WIKI.md Use this command to install skills to a custom directory, useful for AI agents that support skill files but are not built-in. ```shell flight_profiler install-skills --dir /path/to/your/skills ``` -------------------------------- ### Build Wheel Package Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Build the wheel package using make install. After building, install the generated wheel file with pip3. ```shell make install ``` ```shell pip3 install dist/flight_profiler-1.0.0b1-cp39-cp39-macosx_12_0_arm64.whl ``` -------------------------------- ### Enable memory history for torch >= 2.1.0 Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Add at program start to enable sampling of memory allocation history for torch versions 2.1.0 and later. This allows tracing stack information for allocations from program startup. ```python from torch.cuda.memory import _record_memory_history _record_memory_history() ``` -------------------------------- ### torch memory command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Command-line syntax for memory snapshotting or recording memory allocation behavior during method execution. Use -s for snapshot, -r for record, and -f to specify output file path (defaults to snapshot.pickle). ```shell torch memory [-s] [-r module [class] method] [-f ] ``` -------------------------------- ### forceGc Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Forces garbage collection in the Python VM. It triggers a garbage collection cycle. ```APIDOC ## forceGc ### Description Forces garbage collection in the Python VM. It triggers a garbage collection cycle. ### Command ```shell vmtool -a forceGc ``` ### Output Display ```shell vmtool -a forceGc ``` ![img.png](https://raw.githubusercontent.com/alibaba/PyFlightProfiler/refs/heads/main/docs/images/vmtool_gc.png) ``` -------------------------------- ### module filepath Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Outputs the module corresponding to a filename in the injected process, helping users locate methods or variables from exception stacks. ```APIDOC ## module filepath ### Description Outputs the module corresponding to the filename in the injected process, facilitating users to directly locate methods or variables based on exception stacks. ### Method CLI command ### Endpoint `module filepath` ### Parameters #### Positional Arguments - **filepath** (string) - Required - Filename to be escaped ### Output Display Command examples: ```shell # Corresponding module is __main__.py module ~/tt_main.py # Not imported into the specified process module ~/not_exist.py ``` ![img.png](https://raw.githubusercontent.com/alibaba/PyFlightProfiler/refs/heads/main/docs/images/module_exist.png) ![img.png](https://raw.githubusercontent.com/alibaba/PyFlightProfiler/refs/heads/main/docs/images/module_not_exist.png) ``` -------------------------------- ### trace [module] [class] method Source: https://github.com/alibaba/pyflightprofiler/wiki/Home The trace command observes method execution paths and time consumption. It accepts a module and method name, with optional class name and various filtering and depth options. ```APIDOC ## [SHELL] trace [module] [class] method ### Description Observes method execution paths and time consumption for a specified method in a module, optionally within a class. ### Method SHELL ### Endpoint trace module [class] method [-i ] [-nm ] [-et ] [-d ] [-n ] [-f ] ### Parameters #### Path Parameters - **module** (string) - Required - Module where the method is located (e.g., __main__, my.pkg.modulename) - **class** (string) - Optional - Class name where the method is located (e.g., className) - **method** (string) - Required - Method name to observe (e.g., methodName) #### Query Parameters - **-nm, --nested-method** (string) - Optional - Whether to capture nested method with depth restricted to 1 (e.g., -nm nested_method) - **-d, --depth** (integer) - Optional - Display the method call stack, limited to the specified depth. When a depth is specified, the interval parameter is ignored and its value is constrained to 0 (e.g., -d 3) - **-i, --interval** (float) - Optional - Only observe internal method calls with execution time greater than the given interval, defaults to 0.1ms. Smaller intervals increase observation overhead (e.g., -i 1) - **-et, --entrance_time** (float) - Optional - Only display method calls with execution time exceeding the given entrance time (e.g., -et 30) - **-f, --filter** (string) - Optional - Filter parameter expression; only calls passing filter conditions are observed. Reference Python method parameters as (target, *args, **kwargs), needs to return a boolean expression about target, args, and kwargs (e.g., -f "args[0][\"query\"]=='hello'") - **-n, --limits** (integer) - Optional - Maximum number of observed display items, defaults to 10 (e.g., -n 50) ### Response #### Success Response Displays the method execution path and time consumption information. ### Request Example ```shell # Trace module function trace __main__ func # Trace module function and only trace function calls with execution time exceeding 1ms trace __main__ func -i 1 # Trace class function trace __main__ classA func ``` ``` -------------------------------- ### torch profile command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Command-line syntax for sampling execution functions in the torch framework using Torch Profiler. The module and method are required; class is optional. Use -f to specify the output file path, defaulting to trace.json in the current directory. ```shell torch profile module [class] method [-f ] ``` -------------------------------- ### Install and run flight_profiler in conda/virtualenv Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-attach/SKILL.md Two options for using flight_profiler when the target runs under a conda environment like /Users/zy/miniforge3/envs/py310. Option A activates the environment first; Option B uses full paths without activation. ```bash # If the target runs under /Users/zy/miniforge3/envs/py310 # Option A: activate the environment, then install and run conda activate py310 pip3 install flight_profiler flight_profiler # Option B: use the full path directly (no activation needed) /Users/zy/miniforge3/envs/py310/bin/pip3 install flight_profiler /Users/zy/miniforge3/envs/py310/bin/flight_profiler ``` -------------------------------- ### Example 5: File path does not exist Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-module/SKILL.md When the path does not exist on disk, the command fails with this error. ```bash flight_profiler --cmd "module /nonexistent/path.py" --no-color ``` ```text ✗ Parse module argument failed: filepath /nonexistent/path.py does not exist. ``` -------------------------------- ### watch command usage Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Command-line syntax for observing method execution with the watch command. The module and method are required; class is optional. Options include --expr for expression, -nm for nested method, -e for exceptions, -r for raw display, and others. ```shell watch module [class] method [--expr ] [-nm ] [-x ] [-f ] ``` -------------------------------- ### perf [pid] [-f ] [-r ] [-d ] Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Samples the program process to generate flame graphs for optimizing program hotspots, implemented based on py-spy. ```APIDOC ## perf [pid] [-f ] [-r ] [-d ] ### Description Sample profile the program process to generate flame graphs, facilitating users to optimize program hotspots, implemented based on py-spy. ### Method CLI command ### Endpoint `perf [pid] [-f ] [-r ] [-d ]` ### Parameters #### Positional Arguments - **pid** (integer) - Optional - Process ID to analyze, defaults to the injected process #### Options - **-f, --filepath ** (string) - Optional - Path to export flame graph, defaults to flamegraph.svg in current directory - **-r, --rate ** (integer) - Optional - Samples per second, defaults to 100 - **-d, --duration ** (integer) - Optional - Duration in seconds, defaults to waiting for user interruption ### Output Display Command examples: ```shell perf # Output will be exported to ~/flamegraph.svg perf -f ~/flamegraph.svg # Sample for 30s perf -d 30 -f ~/flamegraph.svg ``` Using this command on MacOS requires root permissions for py-spy ![img.png](https://raw.githubusercontent.com/alibaba/PyFlightProfiler/refs/heads/main/docs/images/perf.png) ``` -------------------------------- ### getglobal command syntax Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Shows the command-line syntax for the getglobal command, which observes module global variables or class static variables. Parameters include module, class, field, and options -e, -x, -r, -v. ```shell getglobal module [class] field [-x ] [-e ] [-r] [-v] ``` -------------------------------- ### watch command usage and options Source: https://github.com/alibaba/pyflightprofiler/blob/main/README.md Displays the usage, summary, examples, and options for the PyFlightProfiler watch command. The method location format is `module [class] method`; `--expr` accepts a Python expression with signature `(target, return_obj, cost, *args, **kwargs)` and serves as the body of a return statement. `target` is the class instance for bound methods or None for standalone functions, `return_obj` is the method's return value, `cost` is execution time in milliseconds, and `args`/`kwargs` are the passed arguments. ```text USAGE: 12:01:21 [3/52] watch module [class] method [--expr ] [-nm ] [-x ] [-f ] SUMMARY: Display the input/output args, return object and cost time of method invocation. EXAMPLES: watch __main__ func -x 2 watch __main__ func -f args[0]["query"]=='hello' watch __main__ func -f return_obj['success']==True watch __main__ func --expr return_obj,args -f cost>10 watch __main__ classA func OPTIONS: the module that method locates. the class name if method belongs to class. target method name. --expr contents you want to watch, write python bool statement like input func args is (target, return_obj, cost, *args, **kwargs). default is args,kwargs . -x, --expand object represent tree expand level(default 1), -1 means infinity. -e, --exception short for --exception, only record when method throws exception. -nm, --nested-method watch nested method with depth restrict to 1. -r, --raw display raw output without json format. -v, --verbose display all the nested items in target list or dict. -n, --limits limit the the upperbound of display watched result, default is 10. -f, --filter filter method params&args&return_obj&cost&target, expressions according to --expreg: args[0]=='hello'. ``` -------------------------------- ### trace subcommand usage and options Source: https://github.com/alibaba/pyflightprofiler/blob/main/README.md Shows the CLI usage, examples, and options for the `trace` subcommand. The `-i, --interval` option sets the threshold in milliseconds for displaying inner method calls (default 0.1 ms); a higher interval reduces profiler overhead (observed 5%–20% runtime overhead). The `-d, --depth` option ignores the interval and constrains its value to 0. ```text USAGE: trace module [class] method [-i ] [-nm ] [-et ] [-d ] [-n ] [-f ] SUMMARY: Trace the execution time of specified method invocation. EXAMPLES: trace __main__ func trace __main__ func --interval 1 trace __main__ func -et 30 -i 1 trace __main__ classA func OPTIONS: the module that method locates. the class name if method belongs to class. target method name. -i, --interval display function invocation cost more than ${value} milliseconds, default is 0.1ms. -et, --entrance_time filter function execute cost more than ${value} milliseconds, but on entrance filter. -d, --depth display the method call stack, limited to the specified depth ${value}. When a depth is specified, the ${interval} parameter is ignored and its value is constrained to 0. -nm, --nested-method trace nested method with depth restrict to 1. -f, --filter_expr filter method params expressions, only support filter target&args, write python bool statement like input func args is (target, *args, **kwargs), eg: args[0]=='hello'. -n, --limits threshold of trace method times, default is 10. ``` -------------------------------- ### Decorator limitation example Source: https://github.com/alibaba/pyflightprofiler/wiki/Home This example shows that modifications inside a decorator are not supported because the decorator changes the original function only once. Modifications inside the decorated function are supported. ```python from functools import wraps def adder(func): @wraps(func) def wrapper(*args, **kwargs): # ---------------- new added --------------------- # modification added here is not supported because decorator changes original function executed only once. print(f"calling decorator") # ------------------------------------------------- result = func(*args, **kwargs) + 1 return result return wrapper @adder def target_func(x, y): # modification here is supported. return x + y ``` -------------------------------- ### Run Flight Profiler Source: https://github.com/alibaba/pyflightprofiler/blob/main/docs/DEVELOP.md Execute the flight_profiler command with a process ID (py_pid) to profile it. ```shell flight_profiler py_pid ``` -------------------------------- ### Run flight_profiler stack command Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-stack/SKILL.md Captures a snapshot of stack frames for the specified process and returns immediately. Use --no-color to disable colored output. Requires the flight-profiler-attach skill for setup. ```bash flight_profiler --cmd "stack [options]" --no-color ``` -------------------------------- ### Output of stack -a Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-stack/SKILL.md Example output showing all active asyncio tasks grouped by thread. Tasks are labeled with names from asyncio.create_task(name=...) or Task-N for unnamed tasks, and show their state and coroutine stack frames. ```text ============================================================ Async Coroutine/Task Stacks ============================================================ Thread: async-loop (tid: 0x171daf000) -------------------------------------------------- Task #1: periodic-heartbeat State: WAITING Coroutine: periodic_task Stack (2 frames): File "stack_demo_script.py", line 44, in periodic_task await asyncio.sleep(1) File ".../asyncio/tasks.py", line 649, in sleep return await future Task #2: Task-1 State: WAITING Coroutine: run_async_loop Stack (1 frames): File "stack_demo_script.py", line 53, in run_async_loop await asyncio.gather(*tasks) Task #3: process-item-42 State: WAITING Coroutine: process_item Stack (2 frames): File "stack_demo_script.py", line 38, in process_item await asyncio.sleep(3600) File ".../asyncio/tasks.py", line 649, in sleep return await future Task #4: fetch-api-data State: WAITING Coroutine: fetch_data Stack (2 frames): File "stack_demo_script.py", line 33, in fetch_data await asyncio.sleep(3600) File ".../asyncio/tasks.py", line 649, in sleep return await future ============================================================ ``` -------------------------------- ### Common combinations of -i, -et, -d options Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-trace/SKILL.md Shows typical usage of the trace command with the -et, -i, and -d options to filter output by invocation cost, sub-call cost, and tree depth. The first example filters slow invocations and expensive sub-calls, the second gives a top-level overview, and the third captures everything with -i 0. ```bash # Show only slow invocations, then only their expensive sub-calls trace __main__ MyClass method -et 100 -i 10 -n 3 ``` ```bash # Quick overview: just the top-level breakdown trace __main__ MyClass method -d 2 -n 1 ``` ```bash # Catch everything (debug mode) trace __main__ MyClass method -i 0 -n 1 ``` -------------------------------- ### Invalid reload with new module import Source: https://github.com/alibaba/pyflightprofiler/wiki/Home This example shows a reload that cannot work because it imports the time module, which was not in the original method. Module-level imports are not supported. ```python # ---------------- new added --------------------- import time # ------------------------------------------------ def func(): print(2) # ---------------- new added --------------------- # Cannot work properly because use time module not appear in original method # and we do reload on function level only. print(time.time()) # ------------------------------------------------ ``` -------------------------------- ### Function parameter default value limitation Source: https://github.com/alibaba/pyflightprofiler/wiki/Home This example shows that default values of function parameters are stored in __defaults__, so if they contain function calls, those calls are triggered when the new function is created. ```python def get_default_time(): return "2026-02-01" def my_func(time_str=get_default_time()): # When my_func is modified in place, `get_default_time` function will be called in the new function creation print(time_str) ``` -------------------------------- ### Check target process owner and run with sudo Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-attach/SKILL.md Verify the target process's user and run flight_profiler with sudo if the target is root-owned. Replace with the actual process ID. ```bash # Check target process owner ps -p -o user= # If target is root-owned sudo flight_profiler --cmd "stack" --no-color ``` -------------------------------- ### tt -t module [class] method Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Observes method calls in the specified module over time and space. The module/class/method definitions are the same as in watch/trace. ```APIDOC ## [SHELL] tt -t module [class] method ### Description Observes method calls in the specified module over time and space. The module/class/method definitions are the same as in watch/trace. ### Method SHELL ### Endpoint tt -t module [class] method ### Parameters #### Command Parameters - **-t module [class] method** (string) - Required - Observe method calls in the specified module over time and space. Example: `-t moduleA classA func` - **-nm, --nested-method** (flag) - Optional - Whether capture nested method with depth restrict to 1. Example: `-nm nested_method` - **-n, --limits ** (integer) - Optional - Maximum number of observed display items, defaults to 50. Example: `-n 50` - **-l, --list** (flag) - Optional - Display all method call segments. Example: `-l` - **-i, --index ** (integer) - Optional - Display details of the method call corresponding to the index. Example: `-i 1000` - **-d, --delete ** (integer) - Optional - Delete the call record corresponding to the index. Example: `-d 1000` - **-da, --delete_all** (flag) - Optional - Delete all call records. Example: `-da` - **-r, --raw** (flag) - Optional - Whether to directly display the string representation of the target, i.e., repr(target). Example: `-r` - **-v, --verbose** (flag) - Optional - Whether to display all sub-items of target lists/dictionaries. Example: `-v` - **-x, --expand** (integer) - Optional - expand, depth to display observed objects, defaults to 1, maximum is 4. Example: `-x 2` - **-p, --play** (flag) - Optional - Whether to re-trigger historical calls, used with -i, using the call parameters specified by index. Example: `-i 1000 -p` - **-f, --filter** (string) - Optional - Filter parameter expression, reference watch command. Example: `-f "args[0][\"query\"]=='hello'"` - **-m, --method** (string) - Optional - Filter method name, format is module.class.method, if the method is a class method, class is None, compatible with -l. Example: `-l -m moduleA.classA.methodA` ### Response #### Success Response - **Output** (string) - The observed method call records and details. ### Request Example ```shell # Record module method tt -t __main__ func # Record class method tt -t __main__ A func # Display called method record list tt -l # Display specified call details tt -i 1000 -x 3 # Re-trigger the call with index 1000, using the same input tt -i 1000 -p # Only observe records with return value 'success' and time consumption greater than 10ms tt -t __main__ func -f "return_obj['success']==True and cost>10" # Only observe requests where the first method parameter contains a query field with value "hello" tt -t __main__ func -f "args[0][\"query\"]=='hello'" ``` ``` -------------------------------- ### Use --expr to see target (self) and return value Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-watch/SKILL.md Use --expr target,return_obj to see the class instance (self) and the return value. The target is shown with its attributes. ```bash flight_profiler --cmd "watch __main__ UserService get_user --expr target,return_obj -n 1" --no-color ``` ```text ──────────────────────────────────────────────────────────── ✓ ... method=__main__.UserService.get_user cost=10.831118ms is_exp=False result={ EXPR: target,return_obj TYPE: VALUE: ( UserService({}), { "active": True, "id": 56, "name": "user_56" } ) } ``` -------------------------------- ### Memory Diff Command Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Compares memory size differences between two time points. Takes snapshots before and after the specified interval (10s) and displays the largest differences in descending order. ```shell mem diff --interval 10 --limit 100 --order descending ``` -------------------------------- ### Memory Summary Command Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Statistically analyzes memory usage by variable type. The limit parameter controls the number of TOP items displayed, and order controls sorting (descending/ascending). ```shell mem summary ``` ```shell mem summary --limit 100 --order descending ``` -------------------------------- ### Find all instances of a class Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-vmtool/SKILL.md Uses getInstances with -c to find all instances of the Connection class. Output shows the list of instances with their attributes. ```bash flight_profiler --cmd "vmtool -a getInstances -c __main__ Connection" --no-color ``` ```text EXPR: instances TYPE: VALUE: [ Connection({'host': 'queue', 'port': 5672, 'status': 'error'}), Connection({'host': 'cache', 'port': 6379, 'status': 'idle'}), Connection({'host': 'db-replica', 'port': 5433, 'status': 'active'}), Connection({'host': 'db-primary', 'port': 5432, 'status': 'active'}) ] ``` -------------------------------- ### reload command format Source: https://github.com/alibaba/pyflightprofiler/wiki/Home The reload command is used to modify method execution logic online. It requires the module and method name, with an optional class name and verbose flag. ```shell reload module [class] method [--verbose] ``` -------------------------------- ### getInstances output format Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-vmtool/SKILL.md Shows the expression result block format returned by getInstances, with EXPR, TYPE, and VALUE fields. ```text EXPR: instances TYPE: VALUE: [ Connection({'host': 'queue', 'port': 5672, 'status': 'error'}), Connection({'host': 'cache', 'port': 6379, 'status': 'idle'}), Connection({'host': 'db-replica', 'port': 5433, 'status': 'active'}), Connection({'host': 'db-primary', 'port': 5432, 'status': 'active'}) ] ``` -------------------------------- ### Inspect process tree to identify worker vs launcher Source: https://github.com/alibaba/pyflightprofiler/blob/main/skills/flight-profiler-attach/SKILL.md Use pstree or ps to see parent-child relationships in multi-process architectures. Attach to the worker/child process for request handling or inference, and to the master/launcher for scheduling or management. ```bash # List the process tree to see parent-child relationships pstree -p # Or find all child processes ps --ppid -o pid,cmd # Linux ps -o pid,ppid,command | grep # macOS ``` -------------------------------- ### getglobal Source: https://github.com/alibaba/pyflightprofiler/wiki/Home The getglobal command observes module global variables or class static variables in a running Python process. It supports optional expressions, expansion depth, raw string output, and verbose listing of sub-items. ```APIDOC ## getglobal ### Description The getglobal command observes module global variables or class static variables in a running Python process. It supports optional expressions, expansion depth, raw string output, and verbose listing of sub-items. ### Method CLI command ### Command Syntax ``` getglobal module [class] field [-x ] [-e ] [-r] [-v] ``` ### Parameters #### Positional Parameters - **module** (string) - Required - Module where the field is located (e.g., __main__, my.pkg.modulename) - **class** (string) - Optional - Class name where the field is located (e.g., className) - **field** (string) - Required - Field name (e.g., fieldName) #### Options - **-e, --expr** (string) - Optional - Expression for observing objects, reference Python method parameters as (target), target is the observed object, needs to return a right-value expression about target (e.g., target.fieldA) - **-x, --expand** (integer) - Optional - Depth to display observed objects, defaults to 1, maximum is 4 (e.g., 2) - **-r, --raw** (flag) - Optional - Whether to directly display the string representation of the target - **-v, --verbose** (flag) - Optional - Whether to display all sub-items of target lists/dictionaries ### Examples #### Module variables ``` getglobal __main__ g_list ``` #### Class static variables ``` getglobal __main__ classA static_field ``` ``` -------------------------------- ### GIL Long Tail Loss Monitoring Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Enables GIL lock monitoring with thresholds: first parameter is acquisition time threshold (5ms), second is holding time threshold (5ms). Prints a message when either threshold is exceeded. ```shell gilstat on 5 5 ``` -------------------------------- ### GIL Lock Loss Statistics Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Enables GIL lock loss statistics, outputting per-thread statistics every 5 seconds. Fields include thread_name, takecnt, hold_all, holdavg, take_all, takeavg, drogcnt, drog_all, and dropavg. ```shell gilstat on ``` -------------------------------- ### Analyze thread stacks with stack command (Linux) Source: https://github.com/alibaba/pyflightprofiler/wiki/Home Views Python execution stack information for all threads in the process on Linux. Supports native stack analysis and exporting to a file. The `pid` parameter defaults to the injected process ID; `--native` defaults to False. ```shell stack [pid] [-f ] [--native] ```