Change location of temporary file in pip_cmd_run function

- Imported tempfile module to create a temporary file.
- Replaced the creation of 'test.txt' in the current directory with a temporary file.
- The temporary file is automatically deleted when it is closed, eliminating the need for manual deletion.
This commit is contained in:
bobo.yang 2023-07-26 15:03:20 +08:00
parent 1f841446e2
commit 999edb5129

View File

@ -1,6 +1,8 @@
import os import os
import subprocess import subprocess
import sys import sys
import tempfile
# replace python3 with sys.executable, we will do everything in the same envrionment # replace python3 with sys.executable, we will do everything in the same envrionment
pythonCommand = sys.executable pythonCommand = sys.executable
@ -40,25 +42,17 @@ def pip_cmd_run(pipcmd, with_user: bool, with_local_source: bool):
pipcmd.append("-i") pipcmd.append("-i")
pipcmd.append("https://pypi.tuna.tsinghua.edu.cn/simple") pipcmd.append("https://pypi.tuna.tsinghua.edu.cn/simple")
file = open('test.txt', 'wb') with tempfile.NamedTemporaryFile(delete=True) as temp_file:
try: try:
# before command run, output runnning command # before command run, output runnning command
print("run command: ", *pipcmd) print("run command: ", *pipcmd)
subprocess.run(pipcmd, check=True, stdout=sys.stdout, stderr=file, text=True) subprocess.run(pipcmd, check=True, stdout=sys.stdout, stderr=temp_file, text=True)
return True, ''
file.close() except Exception as error:
os.remove('test.txt') temp_file.flush()
return True, '' error_out = temp_file.read()
except Exception as error: print(error)
file.flush() return False, error_out
file.close()
file = open('test.txt', 'rb')
error_out = file.read()
file.close()
os.remove('test.txt')
print(error)
return False, error_out
def pip_cmd_with_retries(pipcmd, retry_times: int, with_user: bool): def pip_cmd_with_retries(pipcmd, retry_times: int, with_user: bool):