Executing #a# prefixed scripts with random string generation

  • Share this:

Code introduction


Executes files that start with 'a' in a specified directory and generates a random string.


Technology Stack : os, random, string, json, time, random, os, json

Code Type : Python Script Execution

Code Difficulty : Intermediate


                
                    
import os
import sys
import json
import time
import random
import string

def generate_random_string(length):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def list_directory_contents(path):
    return os.listdir(path)

def filter_files(start_with, directory):
    return [file for file in list_directory_contents(directory) if file.startswith(start_with)]

def run_python_script(script_path):
    with open(script_path, 'r') as file:
        exec(file.read())

def generate_timestamp():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

def create_json_object(data):
    return json.dumps(data, indent=4)

def xxx(arg1, arg2, arg3):
    random_string = generate_random_string(10)
    files = filter_files('a', arg1)
    script_path = os.path.join(arg1, random.choice(files))
    run_python_script(script_path)
    timestamp = generate_timestamp()
    data = {
        "type": "Python Script Execution",
        "hard": "中级",
        "explain": "执行指定目录下以'a'开头的文件,并生成一个随机字符串。",
        "tench": "os, random, string, json, time, random, os, json",
        "explain_en": "Executes files that start with 'a' in a specified directory and generates a random string.",
        "tench_en": "os, random, string, json, time, random, os, json"
    }
    return create_json_object(data)

# Example usage:
# xxx('/path/to/directory', 'script.py', 'output.txt')