1. import os
  2. import subprocess
  3. import logging
  4. import json
  5. from datetime import datetime
  6. # Configure logging
  7. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  8. def bootstrap_user_record(user_id, experiment_config_path, script_path):
  9. """
  10. Bootstraps a user record script for an experiment.
  11. Args:
  12. user_id (str): The ID of the user.
  13. experiment_config_path (str): Path to the experiment configuration file (JSON).
  14. script_path (str): Path to the script to be executed.
  15. Returns:
  16. bool: True if the script ran successfully, False otherwise.
  17. """
  18. try:
  19. # Load experiment configuration
  20. with open(experiment_config_path, 'r') as f:
  21. experiment_config = json.load(f)
  22. # Prepare input for the script
  23. input_data = {"user_id": user_id, **experiment_config.get("input_parameters", {})}
  24. # Construct the command to execute the script
  25. command = [script_path] + list(input_data.values())
  26. logging.info(f"Executing script with command: {' '.join(command)}")
  27. # Execute the script
  28. process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  29. stdout, stderr = process.communicate()
  30. # Check the return code
  31. if process.returncode == 0:
  32. logging.info(f"Script executed successfully for user {user_id}.")
  33. logging.debug(f"Script output:\n{stdout}")
  34. return True
  35. else:
  36. logging.error(f"Script failed for user {user_id}. Return code: {process.returncode}")
  37. logging.error(f"Script error output:\n{stderr}")
  38. return False
  39. except FileNotFoundError:
  40. logging.error(f"Script not found at {script_path}")
  41. return False
  42. except json.JSONDecodeError:
  43. logging.error(f"Error decoding JSON from {experiment_config_path}")
  44. return False
  45. except Exception as e:
  46. logging.exception(f"An unexpected error occurred: {e}")
  47. return False
  48. if __name__ == '__main__':
  49. # Example Usage
  50. user_id = "user123"
  51. experiment_config_path = "experiment_config.json"
  52. script_path = "user_record_script.py"
  53. # Create dummy files for testing
  54. with open(experiment_config_path, "w") as f:
  55. json.dump({"input_parameters": {"param1": "value1"}}, f)
  56. with open(script_path, "w") as f:
  57. f.write("""
  58. import sys
  59. user_id = sys.argv[1]
  60. print(f"Processing user: {user_id}")
  61. print(f"Parameter 1: {sys.argv[2]}")
  62. """)
  63. success = bootstrap_user_record(user_id, experiment_config_path, script_path)
  64. if success:
  65. print(f"User record script bootstrapped successfully for {user_id}")
  66. else:
  67. print(f"Failed to bootstrap user record script for {user_id}")

Add your comment