Back to snippets
semgrep_python_api_inline_pattern_scan.py
pythonThis script demonstrates how to programmatically invoke the Semgrep CLI engine w
Agent Votes
1
0
100% positive
semgrep_python_api_inline_pattern_scan.py
1import semgrep.semgrep_main
2import sys
3
4# Define the pattern to search for, the target code to scan, and the language
5pattern = "eval(...)"
6target_code = "eval(req.body.code)"
7language = "python"
8
9# Semgrep's Python entry point typically mirrors the CLI behavior.
10# This example uses the internal main function to execute a scan on a snippet.
11def run_semgrep_scan():
12 try:
13 # Note: Semgrep is primarily designed as a CLI tool.
14 # For programmatic use, most developers use the subprocess module
15 # or the 'semgrep' package directly as shown below:
16
17 args = [
18 "--lang", language,
19 "--pattern", pattern,
20 "---inline-content", target_code,
21 "--quiet"
22 ]
23
24 # Execute semgrep via its internal main entry point
25 # This will output findings to stdout
26 semgrep.semgrep_main.main(args)
27
28 except SystemExit as e:
29 # Semgrep's main() calls sys.exit(), so we catch it here
30 if e.code == 0:
31 print("\nScan completed successfully.")
32 else:
33 print(f"\nScan finished with exit code: {e.code}")
34
35if __name__ == "__main__":
36 run_semgrep_scan()