MCPcopy Create free account
hub / github.com/HKUDS/OpenSpace / run_python

Function run_python

openspace/local_server/main.py:418–516  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

416
417@app.route("/run_python", methods=['POST'])
418def run_python():
419 data = request.json
420 code = data.get('code', None)
421 timeout = data.get('timeout', 30)
422 working_dir = data.get('working_dir', None)
423 env = data.get('env', None)
424 conda_env = data.get('conda_env', None)
425
426 if not code:
427 return jsonify({'status': 'error', 'message': 'Code not supplied!'}), 400
428
429 # Generate unique filename
430 if platform_name == "Windows":
431 temp_filename = os.path.join(tempfile.gettempdir(), f"python_exec_{uuid.uuid4().hex}.py")
432 else:
433 temp_filename = f"/tmp/python_exec_{uuid.uuid4().hex}.py"
434
435 try:
436 with open(temp_filename, 'w') as f:
437 f.write(code)
438
439 # Prepare environment variables
440 exec_env = os.environ.copy()
441 if env:
442 exec_env.update(env)
443
444 # If conda_env is specified, try to use bash/cmd to activate and run
445 # If conda is not available, fall back to system Python
446 if conda_env:
447 activation_cmd = get_conda_activation_prefix(conda_env)
448 # Check if conda activation command is empty (conda not found)
449 if not activation_cmd:
450 logger.warning(f"Conda environment '{conda_env}' requested but conda not found. Using system Python.")
451 conda_env = None # Disable conda and use default path
452
453 if conda_env and get_conda_activation_prefix(conda_env):
454 if platform_name == "Windows":
455 # Windows: use cmd with activation
456 activation_cmd = get_conda_activation_prefix(conda_env)
457 full_cmd = f'{activation_cmd}python "{temp_filename}"'
458 result = subprocess.run(
459 ['cmd', '/c', full_cmd],
460 stdout=subprocess.PIPE,
461 stderr=subprocess.PIPE,
462 text=True,
463 timeout=timeout,
464 cwd=working_dir or os.getcwd(),
465 env=exec_env
466 )
467 else:
468 # Linux/macOS: use bash with activation
469 activation_cmd = get_conda_activation_prefix(conda_env)
470 full_cmd = f'{activation_cmd}python3 "{temp_filename}"'
471 result = subprocess.run(
472 ['/bin/bash', '-c', full_cmd],
473 stdout=subprocess.PIPE,
474 stderr=subprocess.PIPE,
475 text=True,

Callers

nothing calls this directly

Calls 4

getMethod · 0.80
runMethod · 0.80
writeMethod · 0.45

Tested by

no test coverage detected