You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python执行指定非.py文件中的随机代码行?

How to Execute a Random Line of Code from a File in Python

Absolutely, this is totally doable! Here's a straightforward way to pull off what you're asking:

Step-by-Step Solution

  1. Import necessary modules: You'll need random to pick a line at random, plus built-in file handling to read your code file.
  2. Read and clean the code file: Open the "code_lines" file, read all lines, and filter out empty or whitespace-only lines to avoid running blank code.
  3. Select a random valid line: Use random.choice() to pick one working code snippet from the cleaned list.
  4. Execute the line: Use Python's exec() function to run the selected code.

Complete Example Script

Here's a ready-to-use script that implements this logic:

import random

# Read and process the code file
with open("code_lines", "r") as f:
    # Strip whitespace and skip empty lines
    valid_code_lines = [line.strip() for line in f if line.strip()]

# Check if there are any lines to execute
if valid_code_lines:
    selected_line = random.choice(valid_code_lines)
    print(f"Running this code: {selected_line}")
    exec(selected_line)
else:
    print("Whoops, the code_lines file is empty or only has whitespace!")

Key Notes to Keep in Mind

  • Security Alert: Be cautious with exec()! If the "code_lines" file can be edited by untrusted people, this could let malicious code run. Only use this with files you fully control.
  • Valid Code Requirement: Each line in your file needs to be a standalone, valid Python statement. Multi-line code blocks won't work with this approach—you'd need to adjust to read code chunks instead of single lines.
  • Error Handling: To catch syntax errors in your code lines, add a try-except block around the exec() call:
try:
    exec(selected_line)
except SyntaxError as e:
    print(f"Invalid code line: {selected_line}\nError message: {e}")

That should get you up and running smoothly. Let me know if you hit any snags!

内容的提问来源于stack exchange,提问作者Harry Dogerman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:38:49