xd11yggy commited on
Commit
70eaa57
·
verified ·
1 Parent(s): 0a827ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -12
app.py CHANGED
@@ -3,6 +3,7 @@ import subprocess
3
  import tempfile
4
  import shutil
5
  import traceback
 
6
 
7
  class CodeExecutor:
8
  def __init__(self):
@@ -11,17 +12,12 @@ class CodeExecutor:
11
  def _install_packages(self, packages):
12
  for package in packages:
13
  try:
14
- subprocess.check_call(["pip", "install", package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
 
15
  except subprocess.CalledProcessError as e:
16
  raise Exception(f"Error installing package {package}: {e}")
17
 
18
- def _uninstall_packages(self, packages):
19
- for package in packages:
20
- try:
21
- subprocess.check_call(["pip", "uninstall", "-y", package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
22
- except subprocess.CalledProcessError as e:
23
- raise Exception(f"Error uninstalling package {package}: {e}")
24
-
25
  def _execute_code(self, code, inputs):
26
  temp_file = f"{self.temp_dir.name}/temp.py"
27
  with open(temp_file, "w") as f:
@@ -54,12 +50,9 @@ class CodeExecutor:
54
  packages = []
55
  else:
56
  packages = [p.strip() for p in packages.split(",")]
57
- if packages:
58
- self._install_packages(packages)
59
  input_values = [i.strip() for i in inputs.split(",")] if inputs else []
60
  output = self._execute_code(code, input_values)
61
- if packages:
62
- self._uninstall_packages(packages)
63
  return output
64
  except Exception as e:
65
  return f"Error: {str(e)}"
 
3
  import tempfile
4
  import shutil
5
  import traceback
6
+ import importlib.util
7
 
8
  class CodeExecutor:
9
  def __init__(self):
 
12
  def _install_packages(self, packages):
13
  for package in packages:
14
  try:
15
+ spec = importlib.util.find_spec(package)
16
+ if spec is None:
17
+ subprocess.check_call(["pip", "install", package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
18
  except subprocess.CalledProcessError as e:
19
  raise Exception(f"Error installing package {package}: {e}")
20
 
 
 
 
 
 
 
 
21
  def _execute_code(self, code, inputs):
22
  temp_file = f"{self.temp_dir.name}/temp.py"
23
  with open(temp_file, "w") as f:
 
50
  packages = []
51
  else:
52
  packages = [p.strip() for p in packages.split(",")]
53
+ self._install_packages(packages)
 
54
  input_values = [i.strip() for i in inputs.split(",")] if inputs else []
55
  output = self._execute_code(code, input_values)
 
 
56
  return output
57
  except Exception as e:
58
  return f"Error: {str(e)}"