Вот мой код. Я создаю класс ExecWrapper для выполнения команд оболочки в Python и пытаюсь выполнить три команды следующим образом. Их выходные данные кажутся конфликтными.
Код: Выделить всё
import subprocess
class ExecWrapper:
def __init__(
self,
subprocess_args: dict = None,
):
if subprocess_args is None:
self.subprocess_args = {}
else:
self.subprocess_args = subprocess_args
def __call__(self, cmd, raise_error=True, **kwargs):
try:
combined_args = {**self.subprocess_args, **kwargs}
output = subprocess.run(cmd, **combined_args)
return output
except subprocess.CalledProcessError as e:
if raise_error:
print(f"Error: {e}")
print(f"Error stdout: {e.stdout}")
print(f"Error stderr: {e.stderr}")
raise e
exec_wrapper = ExecWrapper(
subprocess_args={
"check": True,
"shell": True,
"capture_output": True,
"text": True,
}
)
# The first command
print(exec_wrapper(cmd="pwd ; cd / ; pwd", shell=True))
# The second command
print(exec_wrapper(cmd="which python ; source /home/gaodawei/miniconda3/bin/activate astropy__astropy__3.1 ; which python", shell=True))
# The third command
print(exec_wrapper(cmd="which python ; . /home/gaodawei/DAIL-SweBench/miniconda3/bin/activate astropy__astropy__3.1 ; which python", shell=True))
Код: Выделить всё
CompletedProcess(args='pwd ; cd / ; pwd', returncode=0, stdout='/home/gaodawei/SweBench\n/\n', stderr='')
CompletedProcess(args='which python ; source /home/gaodawei/DAIL-SweBench/miniconda3/bin/activate astropy__astropy__3.1 ; which python', returncode=0, stdout='/home/gaodawei/miniconda3/envs/swe/bin/python\n/home/gaodawei/miniconda3/envs/swe/bin/python\n', stderr='/bin/sh: 1: source: not found\n')
CompletedProcess(args='which python ; . /home/gaodawei/DAIL-SweBench/miniconda3/bin/activate astropy__astropy__3.1 ; which python', returncode=0, stdout='/home/gaodawei/miniconda3/envs/swe/bin/python\n/home/gaodawei/DAIL-SweBench/miniconda3/bin/python\n', stderr='')
- В первой команде cd / успешно меняет каталог
- Во второй команде команда source не поддерживается
- Поэтому в третьей команде я меняю source на ., и это работает. Однако команда who python не выводит ожидаемый результат /home/gaodawei/miniconda3/envs/astropy__astropy__3.1/bin/python
Поэтому я не понимаю, почему третья команда не удалась. Похоже, что среда Python изменилась с /home/gaodawei/miniconda3/envs/swe/bin/python на /home/gaodawei/DAIL-SweBench/miniconda3/bin/python, но не удалось активируйте среду с именем astropy__astropy__3.1
Обновить
Я хочу сказать, третья команда не активирует ожидаемую среду (в subproces.run вместо этого активируется базовая среда).
Однако, когда я запускаю третью команду в своем терминале, она переключается на среду с именем astropy__astropy__3.1
Подробнее здесь: https://stackoverflow.com/questions/791 ... n-properly
Мобильная версия