import os
import subprocess
import logging
import json
from datetime import datetime
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def bootstrap_user_record(user_id, experiment_config_path, script_path):
"""
Bootstraps a user record script for an experiment.
Args:
user_id (str): The ID of the user.
experiment_config_path (str): Path to the experiment configuration file (JSON).
script_path (str): Path to the script to be executed.
Returns:
bool: True if the script ran successfully, False otherwise.
"""
try:
# Load experiment configuration
with open(experiment_config_path, 'r') as f:
experiment_config = json.load(f)
# Prepare input for the script
input_data = {"user_id": user_id, **experiment_config.get("input_parameters", {})}
# Construct the command to execute the script
command = [script_path] + list(input_data.values())
logging.info(f"Executing script with command: {' '.join(command)}")
# Execute the script
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()
# Check the return code
if process.returncode == 0:
logging.info(f"Script executed successfully for user {user_id}.")
logging.debug(f"Script output:\n{stdout}")
return True
else:
logging.error(f"Script failed for user {user_id}. Return code: {process.returncode}")
logging.error(f"Script error output:\n{stderr}")
return False
except FileNotFoundError:
logging.error(f"Script not found at {script_path}")
return False
except json.JSONDecodeError:
logging.error(f"Error decoding JSON from {experiment_config_path}")
return False
except Exception as e:
logging.exception(f"An unexpected error occurred: {e}")
return False
if __name__ == '__main__':
# Example Usage
user_id = "user123"
experiment_config_path = "experiment_config.json"
script_path = "user_record_script.py"
# Create dummy files for testing
with open(experiment_config_path, "w") as f:
json.dump({"input_parameters": {"param1": "value1"}}, f)
with open(script_path, "w") as f:
f.write("""
import sys
user_id = sys.argv[1]
print(f"Processing user: {user_id}")
print(f"Parameter 1: {sys.argv[2]}")
""")
success = bootstrap_user_record(user_id, experiment_config_path, script_path)
if success:
print(f"User record script bootstrapped successfully for {user_id}")
else:
print(f"Failed to bootstrap user record script for {user_id}")
Add your comment