StaticFG

0.9.5 · active · verified Fri Apr 17

StaticFG is a Python library (current version 0.9.5) designed to generate control flow graphs (CFGs) for Python 3 programs. It parses Python source code, builds an Abstract Syntax Tree (AST), and then transforms it into a CFG, which can be visualized using Graphviz. The project is actively maintained with a moderate release cadence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to build a control flow graph from a Python string and attempt to visualize it as a PDF. Note that the Graphviz *system tool* (providing the `dot` command) must be installed and in your system's PATH for visualization to succeed.

import os
from staticfg import CFGBuilder

# Define a simple Python function as a string
code = """
def greet(name):
    if name:
        message = f"Hello, {name}!"
    else:
        message = "Hello, World!"
    print(message)
"""

# Build the CFG from the source string
# The first argument 'greet_cfg' is the name of the CFG (often the function name)
# The second argument is the source code string
cfg = CFGBuilder().build_from_src('greet_cfg', code)

# To visualize, you need the Graphviz system tool installed and in your PATH.
# The output will be 'greet_cfg.pdf' in the current directory.
try:
    cfg.build_visual('greet_cfg', 'pdf')
    print("CFG 'greet_cfg.pdf' generated successfully.")
except Exception as e:
    print(f"Could not build visual graph. Make sure Graphviz (dot command) is installed and in your PATH. Error: {e}")
    # In a real application, you might log this error or notify the user.

view raw JSON →