jupyterlite / xeus-python-kernel

xeus-python in JupyterLite
https://xeus-python-kernel.readthedocs.io
BSD 3-Clause "New" or "Revised" License
30 stars 19 forks source link

Use shutil.which() in subprocess.check_call() when executing mamba/micromamba/conda #103

Closed vasiljevic closed 1 year ago

vasiljevic commented 1 year ago

This PR implement a [recommendation](https://docs.python.org/3/library/subprocess.html#:~:text=For%20maximum%20reliability%2C%20use%20a%20fully%20qualified%20path%20for%20the%20executable.%20To%20search%20for%20an%20unqualified%20name%20on%20PATH%2C%20use%20shutil.which()) from the Python documentation for the Popen constructor: "For maximum reliability, use a fully qualified path for the executable. To search for an unqualified name on PATH, use shutil.which()".

Practically, this PR fixes conda/mamba execution on Windows as we can see from the following examples.

Linux:

username:~$ conda --version
conda 22.11.1
username:~$ python -c "import subprocess; subprocess.check_call(['conda','--version'])"
conda 22.11.1
username:~$ python -c "import subprocess; import shutil; subprocess.check_call([shutil.which('conda'),'--version'])"
conda 22.11.1

Windows:

C:\Users\un>conda --version
conda 22.9.0

C:\Users\un>python -c "import subprocess; subprocess.check_call(['conda','--version'])"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\neboj\anaconda3\envs\build-env\Lib\subprocess.py", line 408, in check_call
    retcode = call(*popenargs, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\neboj\anaconda3\envs\build-env\Lib\subprocess.py", line 389, in call
    with Popen(*popenargs, **kwargs) as p:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\neboj\anaconda3\envs\build-env\Lib\subprocess.py", line 1022, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\neboj\anaconda3\envs\build-env\Lib\subprocess.py", line 1491, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [WinError 2] The system cannot find the file specified

C:\Users\un>python -c "import subprocess; import shutil; subprocess.check_call([shutil.which('conda'),'--version'])"
conda 22.9.0