execute_cli 727 B

123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import time
  5. import requests
  6. # Read the Python code from STDIN
  7. code = sys.stdin.read()
  8. # Set the default kernel ID
  9. kernel_id = 'default'
  10. # try 5 times until success
  11. PORT = os.environ.get('JUPYTER_EXEC_SERVER_PORT')
  12. POST_URL = f'http://localhost:{PORT}/execute'
  13. for i in range(5):
  14. try:
  15. response = requests.post(POST_URL, json={'kernel_id': kernel_id, 'code': code})
  16. except requests.exceptions.ConnectionError:
  17. time.sleep(1)
  18. continue
  19. # if "500: Internal Server Error" is not in the response, break the loop
  20. if '500: Internal Server Error' not in response.text:
  21. break
  22. time.sleep(1)
  23. # Print the response
  24. print(str(response.text))