Run a command and track its carbon emissions. This command wraps any executable and measures the process's total power consumption during its execution. When the command completes, a summary report is displayed and emissions data is saved to a CSV file. Note: This tracks proce
(
ctx: typer.Context,
log_level: Annotated[
str,
typer.Option(help="Log level (critical, error, warning, info, debug)"),
] = "error",
offline: bool = False,
**tracker_args,
)
| 12 | |
| 13 | |
| 14 | def run_and_monitor( |
| 15 | ctx: typer.Context, |
| 16 | log_level: Annotated[ |
| 17 | str, |
| 18 | typer.Option(help="Log level (critical, error, warning, info, debug)"), |
| 19 | ] = "error", |
| 20 | offline: bool = False, |
| 21 | **tracker_args, |
| 22 | ): |
| 23 | """ |
| 24 | Run a command and track its carbon emissions. |
| 25 | |
| 26 | This command wraps any executable and measures the process's total power |
| 27 | consumption during its execution. When the command completes, a summary |
| 28 | report is displayed and emissions data is saved to a CSV file. |
| 29 | |
| 30 | Note: This tracks process-level emissions (only the specific command), not the |
| 31 | entire machine. For machine-level tracking, use the `monitor` command. |
| 32 | |
| 33 | Examples: |
| 34 | |
| 35 | Do not use quotes around the command. Use -- to separate CodeCarbon args. |
| 36 | |
| 37 | # Run any shell command: |
| 38 | codecarbon monitor -- ./benchmark.sh |
| 39 | |
| 40 | # Commands with arguments (use single quotes for special chars): |
| 41 | codecarbon monitor -- python -c 'print("Hello World!")' |
| 42 | |
| 43 | # Pipe the command output: |
| 44 | codecarbon monitor -- npm run test > output.txt |
| 45 | |
| 46 | # Display the CodeCarbon detailed logs: |
| 47 | codecarbon monitor --log-level debug -- python --version |
| 48 | |
| 49 | The emissions data is appended to emissions.csv (default) in the current |
| 50 | directory. The file path is shown in the final report. |
| 51 | """ |
| 52 | # Suppress all CodeCarbon logs during execution |
| 53 | from codecarbon.external.logger import set_logger_level |
| 54 | |
| 55 | set_logger_level(log_level) |
| 56 | |
| 57 | # Get the command from remaining args |
| 58 | command = ctx.args |
| 59 | |
| 60 | if not command: |
| 61 | print( |
| 62 | "ERROR: No command provided. Use: codecarbon monitor -- <command>", |
| 63 | file=sys.stderr, |
| 64 | ) |
| 65 | raise typer.Exit(1) |
| 66 | |
| 67 | tracker_cls = OfflineEmissionsTracker if offline else EmissionsTracker |
| 68 | tracker = tracker_cls( |
| 69 | log_level=log_level, |
| 70 | save_to_logger=False, |
| 71 | tracking_mode="process", |