execute_cli.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. import sys
  3. import time
  4. import traceback
  5. import requests
  6. # Read the Python code from STDIN
  7. code = sys.stdin.read()
  8. def execute_code(code, print_output=True):
  9. PORT = os.environ.get('JUPYTER_EXEC_SERVER_PORT')
  10. POST_URL = f'http://localhost:{PORT}/execute'
  11. # Set the default kernel ID
  12. kernel_id = 'default'
  13. output = ''
  14. for i in range(3):
  15. try:
  16. response = requests.post(
  17. POST_URL, json={'kernel_id': kernel_id, 'code': code}
  18. )
  19. output = response.text
  20. if '500: Internal Server Error' not in output:
  21. if print_output:
  22. print(output)
  23. break
  24. except requests.exceptions.ConnectionError:
  25. if i == 2:
  26. traceback.print_exc()
  27. time.sleep(2)
  28. else:
  29. if not output:
  30. with open('/opendevin/logs/jupyter_execute_server.log', 'r') as f:
  31. output = f.read()
  32. print('Failed to connect to the Jupyter server', output)
  33. if jupyter_pwd := os.environ.get('JUPYTER_PWD'):
  34. execute_code(
  35. f'import os\nos.environ["JUPYTER_PWD"] = "{jupyter_pwd}"\n', print_output=False
  36. )
  37. execute_code(code)