惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Apple Machine Learning Research
Apple Machine Learning Research
D
Docker
美团技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
月光博客
月光博客
J
Java Code Geeks
V
V2EX
IT之家
IT之家
T
Troy Hunt's Blog
D
DataBreaches.Net
Cloudbric
Cloudbric
Blog — PlanetScale
Blog — PlanetScale
H
Hackread – Cybersecurity News, Data Breaches, AI and More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
The GitHub Blog
The GitHub Blog
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
博客园 - Franky
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Help Net Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
aimingoo的专栏
aimingoo的专栏
S
Security Affairs
Hugging Face - Blog
Hugging Face - Blog
Forbes - Security
Forbes - Security
AI
AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
腾讯CDC
H
Heimdal Security Blog
The Cloudflare Blog
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
Webroot Blog
Webroot Blog
有赞技术团队
有赞技术团队
The Hacker News
The Hacker News
Microsoft Security Blog
Microsoft Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
罗磊的独立博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
Help Net Security
Help Net Security
T
The Exploit Database - CXSecurity.com

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial TIL: ABlog for Sphinx - Documentation as a Blog Platform
TIL: Python eval(), exec(), and compile() Functions
2021-03-14 · via Stonecharioteer on Tech

Python Dynamic Code Execution Functions

What’s the difference between eval, exec, and compile? - Stack Overflow

Understanding the three core functions for dynamic code execution in Python:

eval() - Expression Evaluation

Purpose: Evaluates a single Python expression and returns the result

1
2
3
result = eval("2 + 3 * 4")  # Returns 14
x = 5
result = eval("x * 2")      # Returns 10

Characteristics:

  • Single Expression: Only works with expressions, not statements
  • Return Value: Always returns a value
  • Use Cases: Mathematical calculations, simple expressions
  • Limitations: Cannot handle statements like assignments or loops

exec() - Statement Execution

Purpose: Executes Python statements (does not return a value)

1
2
3
4
5
exec("x = 10; y = 20; print(x + y)")  # Prints: 30
exec("""
for i in range(3):
    print(f"Hello {i}")
""")

Characteristics:

  • Multiple Statements: Can execute complex code blocks
  • No Return Value: Returns None
  • Use Cases: Dynamic code execution, configuration scripts
  • Flexibility: Can handle any valid Python code

compile() - Code Object Creation

Purpose: Compiles source code into code objects for repeated execution

1
2
3
4
5
6
# Compile once, execute multiple times
code = compile("x * 2", "<string>", "eval")
x = 5
result1 = eval(code)  # Returns 10
x = 10
result2 = eval(code)  # Returns 20

Modes:

  • ’eval’: For expressions (use with eval())
  • ’exec’: For statements (use with exec())
  • ‘single’: For single interactive statements

Performance Considerations

Compilation Overhead:

  • eval() and exec() compile code every time
  • compile() allows pre-compilation for repeated use
  • Significant performance improvement for repeated execution

Example - Repeated Execution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import timeit

# Without compile() - slower
def slow_version():
    for i in range(1000):
        eval("2 + 3 * 4")

# With compile() - faster
code = compile("2 + 3 * 4", "<string>", "eval")
def fast_version():
    for i in range(1000):
        eval(code)

Security Considerations

Major Risks:

  • Code Injection: User input can execute arbitrary code
  • System Access: Malicious code can access file system, network
  • Data Exposure: Can access and modify global variables

Safer Alternatives:

1
2
3
4
5
6
7
8
# Restricted globals and locals
safe_globals = {"__builtins__": {}}
safe_locals = {"x": 10, "y": 20}
result = eval("x + y", safe_globals, safe_locals)

# Use ast.literal_eval for safe data parsing
import ast
data = ast.literal_eval("{'key': 'value'}")  # Only literals

Best Practices

  1. Avoid When Possible: Use alternative approaches first
  2. Sanitize Input: Never execute untrusted user input
  3. Restrict Scope: Use limited globals and locals dictionaries
  4. Use ast.literal_eval: For parsing data structures safely
  5. Pre-compile: Use compile() for repeated execution

These functions provide powerful dynamic execution capabilities but require careful consideration of security and performance implications.