请求将指定Shell代码转换为Python代码(附功能说明)
Convert Your Shell Command to Python
Let's start by breaking down what your original shell script does, then translate it into clean, readable Python code that matches the exact functionality:
Original Shell Command:
line="ddtest-7.0" find . -name "*.json" -exec grep -l "project_name.*\"$line\"" {} \; | grep -vw project
Core Functionality Recap:
- Recursively scans the current directory and all subdirectories for
.jsonfiles - Checks each file for entries matching the pattern
project_name.*"ddtest-7.0"(e.g.,"project_name": "ddtest-7.0"in JSON) - Filters out any files whose name contains the word "project"
Equivalent Python Code:
import os import re def find_matching_json(target_project): # Build a safe regex pattern to avoid issues with special characters in the project name regex_pattern = re.compile(r'project_name.*?"{}"'.format(re.escape(target_project))) matches = [] # Walk through every directory starting from the current working folder for root, _, files in os.walk('.'): for filename in files: # Skip files with "project" in their name (case-insensitive) if 'project' in filename.lower(): continue # Only process JSON files if filename.endswith('.json'): full_path = os.path.join(root, filename) try: # Read the file content with UTF-8 encoding to handle special characters with open(full_path, 'r', encoding='utf-8') as file: content = file.read() # Check if our pattern exists in the file if regex_pattern.search(content): matches.append(full_path) except Exception as e: # Gracefully handle unreadable files print(f"Warning: Could not read {full_path} - {str(e)}") return matches # Set your target project name here target = "ddtest-7.0" result_files = find_matching_json(target) # Print all matching file paths for file in result_files: print(file)
Key Details About This Python Implementation:
- Regex Safety: Uses
re.escape()to handle special characters in your project name (like hyphens or dots) so they don't break the pattern matching. - Case-Insensitive Filtering: The check
'project' in filename.lower()mirrors your originalgrep -vw projectbehavior, excluding files likeProject.jsonorPROJECT_metadata.json. - Robust Error Handling: Includes a try/except block to catch issues like permission errors or corrupted files, which makes the script more reliable than the shell version.
- Modular Design: The function is reusable—you can easily pass different project names to it without rewriting the whole script.
If your JSON uses single quotes instead of double quotes, just adjust the regex pattern to r"project_name.*?'{}'" to match that format.
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

