如何让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
- Import necessary modules: You'll need
randomto pick a line at random, plus built-in file handling to read your code file. - 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.
- Select a random valid line: Use
random.choice()to pick one working code snippet from the cleaned list. - 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
相关产品推荐
相关产品推荐

