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,23 +42,15 @@ 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)
file.close()
os.remove('test.txt')
return True, '' return True, ''
except Exception as error: except Exception as error:
file.flush() temp_file.flush()
file.close() error_out = temp_file.read()
file = open('test.txt', 'rb')
error_out = file.read()
file.close()
os.remove('test.txt')
print(error) print(error)
return False, error_out return False, error_out