##// END OF EJS Templates
Remove branching over whitespace in executable path
Blazej Michalik -
Show More
@@ -1,113 +1,112 b''
1 """Implementation of packaging-related magic functions.
1 """Implementation of packaging-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2018 The IPython Development Team.
4 # Copyright (c) 2018 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import re
11 import re
12 import shlex
12 import shlex
13 import sys
13 import sys
14 from pathlib import Path
14 from pathlib import Path
15
15
16 from IPython.core.magic import Magics, magics_class, line_magic
16 from IPython.core.magic import Magics, magics_class, line_magic
17
17
18
18
19 def _is_conda_environment():
19 def _is_conda_environment():
20 """Return True if the current Python executable is in a conda env"""
20 """Return True if the current Python executable is in a conda env"""
21 # TODO: does this need to change on windows?
21 # TODO: does this need to change on windows?
22 return Path(sys.prefix, "conda-meta", "history").exists()
22 return Path(sys.prefix, "conda-meta", "history").exists()
23
23
24
24
25 def _get_conda_executable():
25 def _get_conda_executable():
26 """Find the path to the conda executable"""
26 """Find the path to the conda executable"""
27 # Check if there is a conda executable in the same directory as the Python executable.
27 # Check if there is a conda executable in the same directory as the Python executable.
28 # This is the case within conda's root environment.
28 # This is the case within conda's root environment.
29 conda = Path(sys.executable).parent / "conda"
29 conda = Path(sys.executable).parent / "conda"
30 if conda.is_file():
30 if conda.is_file():
31 return str(conda)
31 return str(conda)
32
32
33 # Otherwise, attempt to extract the executable from conda history.
33 # Otherwise, attempt to extract the executable from conda history.
34 # This applies in any conda environment.
34 # This applies in any conda environment.
35 history = Path(sys.prefix, "conda-meta", "history").read_text()
35 history = Path(sys.prefix, "conda-meta", "history").read_text()
36 match = re.search(
36 match = re.search(
37 r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]",
37 r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]",
38 history,
38 history,
39 flags=re.MULTILINE,
39 flags=re.MULTILINE,
40 )
40 )
41 if match:
41 if match:
42 return match.groupdict()["command"]
42 return match.groupdict()["command"]
43
43
44 # Fallback: assume conda is available on the system path.
44 # Fallback: assume conda is available on the system path.
45 return "conda"
45 return "conda"
46
46
47
47
48 CONDA_COMMANDS_REQUIRING_PREFIX = {
48 CONDA_COMMANDS_REQUIRING_PREFIX = {
49 'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
49 'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
50 }
50 }
51 CONDA_COMMANDS_REQUIRING_YES = {
51 CONDA_COMMANDS_REQUIRING_YES = {
52 'install', 'remove', 'uninstall', 'update', 'upgrade',
52 'install', 'remove', 'uninstall', 'update', 'upgrade',
53 }
53 }
54 CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
54 CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
55 CONDA_YES_FLAGS = {'-y', '--y'}
55 CONDA_YES_FLAGS = {'-y', '--y'}
56
56
57
57
58 @magics_class
58 @magics_class
59 class PackagingMagics(Magics):
59 class PackagingMagics(Magics):
60 """Magics related to packaging & installation"""
60 """Magics related to packaging & installation"""
61
61
62 @line_magic
62 @line_magic
63 def pip(self, line):
63 def pip(self, line):
64 """Run the pip package manager within the current kernel.
64 """Run the pip package manager within the current kernel.
65
65
66 Usage:
66 Usage:
67 %pip install [pkgs]
67 %pip install [pkgs]
68 """
68 """
69 python = sys.executable
69 python = sys.executable
70 if " " in python:
70 if sys.platform == "win32":
71 if sys.platform == "win32":
71 python = '"' + python + '"'
72 python = '"' + python + '"'
72 else:
73 else:
73 python = shlex.quote(python)
74 python = shlex.quote(python)
75
74
76 self.shell.system(" ".join([python, "-m", "pip", line]))
75 self.shell.system(" ".join([python, "-m", "pip", line]))
77
76
78 print("Note: you may need to restart the kernel to use updated packages.")
77 print("Note: you may need to restart the kernel to use updated packages.")
79
78
80 @line_magic
79 @line_magic
81 def conda(self, line):
80 def conda(self, line):
82 """Run the conda package manager within the current kernel.
81 """Run the conda package manager within the current kernel.
83
82
84 Usage:
83 Usage:
85 %conda install [pkgs]
84 %conda install [pkgs]
86 """
85 """
87 if not _is_conda_environment():
86 if not _is_conda_environment():
88 raise ValueError("The python kernel does not appear to be a conda environment. "
87 raise ValueError("The python kernel does not appear to be a conda environment. "
89 "Please use ``%pip install`` instead.")
88 "Please use ``%pip install`` instead.")
90
89
91 conda = _get_conda_executable()
90 conda = _get_conda_executable()
92 args = shlex.split(line)
91 args = shlex.split(line)
93 command = args[0] if len(args) > 0 else ""
92 command = args[0] if len(args) > 0 else ""
94 args = args[1:] if len(args) > 1 else [""]
93 args = args[1:] if len(args) > 1 else [""]
95
94
96 extra_args = []
95 extra_args = []
97
96
98 # When the subprocess does not allow us to respond "yes" during the installation,
97 # When the subprocess does not allow us to respond "yes" during the installation,
99 # we need to insert --yes in the argument list for some commands
98 # we need to insert --yes in the argument list for some commands
100 stdin_disabled = getattr(self.shell, 'kernel', None) is not None
99 stdin_disabled = getattr(self.shell, 'kernel', None) is not None
101 needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
100 needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
102 has_yes = set(args).intersection(CONDA_YES_FLAGS)
101 has_yes = set(args).intersection(CONDA_YES_FLAGS)
103 if stdin_disabled and needs_yes and not has_yes:
102 if stdin_disabled and needs_yes and not has_yes:
104 extra_args.append("--yes")
103 extra_args.append("--yes")
105
104
106 # Add --prefix to point conda installation to the current environment
105 # Add --prefix to point conda installation to the current environment
107 needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
106 needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
108 has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
107 has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
109 if needs_prefix and not has_prefix:
108 if needs_prefix and not has_prefix:
110 extra_args.extend(["--prefix", sys.prefix])
109 extra_args.extend(["--prefix", sys.prefix])
111
110
112 self.shell.system(' '.join([conda, command] + extra_args + args))
111 self.shell.system(' '.join([conda, command] + extra_args + args))
113 print("\nNote: you may need to restart the kernel to use updated packages.")
112 print("\nNote: you may need to restart the kernel to use updated packages.")
General Comments 0
You need to be logged in to leave comments. Login now