##// END OF EJS Templates
core.magics.packaging: improve style
Blazej Michalik -
Show More
@@ -1,102 +1,102 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
14
15 from pathlib import Path
15 from pathlib import Path
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.isfile():
30 if conda.isfile():
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 R = re.compile(r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]")
35 R = re.compile(r"^#\s*cmd:\s*(?P<command>.*conda)\s[create|install]")
36 with open(Path(sys.prefix, 'conda-meta', 'history')) as f:
36 with open(Path(sys.prefix, "conda-meta", "history")) as f:
37 for line in f:
37 for line in f:
38 match = R.match(line)
38 match = R.match(line)
39 if match:
39 if match:
40 return match.groupdict()['command']
40 return match.groupdict()['command']
41
41
42 # Fallback: assume conda is available on the system path.
42 # Fallback: assume conda is available on the system path.
43 return "conda"
43 return "conda"
44
44
45
45
46 CONDA_COMMANDS_REQUIRING_PREFIX = {
46 CONDA_COMMANDS_REQUIRING_PREFIX = {
47 'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
47 'install', 'list', 'remove', 'uninstall', 'update', 'upgrade',
48 }
48 }
49 CONDA_COMMANDS_REQUIRING_YES = {
49 CONDA_COMMANDS_REQUIRING_YES = {
50 'install', 'remove', 'uninstall', 'update', 'upgrade',
50 'install', 'remove', 'uninstall', 'update', 'upgrade',
51 }
51 }
52 CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
52 CONDA_ENV_FLAGS = {'-p', '--prefix', '-n', '--name'}
53 CONDA_YES_FLAGS = {'-y', '--y'}
53 CONDA_YES_FLAGS = {'-y', '--y'}
54
54
55
55
56 @magics_class
56 @magics_class
57 class PackagingMagics(Magics):
57 class PackagingMagics(Magics):
58 """Magics related to packaging & installation"""
58 """Magics related to packaging & installation"""
59
59
60 @line_magic
60 @line_magic
61 def pip(self, line):
61 def pip(self, line):
62 """Run the pip package manager within the current kernel.
62 """Run the pip package manager within the current kernel.
63
63
64 Usage:
64 Usage:
65 %pip install [pkgs]
65 %pip install [pkgs]
66 """
66 """
67 self.shell.system(' '.join([sys.executable, '-m', 'pip', line]))
67 self.shell.system(' '.join([sys.executable, '-m', 'pip', line]))
68 print("Note: you may need to restart the kernel to use updated packages.")
68 print("Note: you may need to restart the kernel to use updated packages.")
69
69
70 @line_magic
70 @line_magic
71 def conda(self, line):
71 def conda(self, line):
72 """Run the conda package manager within the current kernel.
72 """Run the conda package manager within the current kernel.
73
73
74 Usage:
74 Usage:
75 %conda install [pkgs]
75 %conda install [pkgs]
76 """
76 """
77 if not _is_conda_environment():
77 if not _is_conda_environment():
78 raise ValueError("The python kernel does not appear to be a conda environment. "
78 raise ValueError("The python kernel does not appear to be a conda environment. "
79 "Please use ``%pip install`` instead.")
79 "Please use ``%pip install`` instead.")
80
80
81 conda = _get_conda_executable()
81 conda = _get_conda_executable()
82 args = shlex.split(line)
82 args = shlex.split(line)
83 command = args[0]
83 command = args[0]
84 args = args[1:]
84 args = args[1:]
85 extra_args = []
85 extra_args = []
86
86
87 # When the subprocess does not allow us to respond "yes" during the installation,
87 # When the subprocess does not allow us to respond "yes" during the installation,
88 # we need to insert --yes in the argument list for some commands
88 # we need to insert --yes in the argument list for some commands
89 stdin_disabled = getattr(self.shell, 'kernel', None) is not None
89 stdin_disabled = getattr(self.shell, 'kernel', None) is not None
90 needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
90 needs_yes = command in CONDA_COMMANDS_REQUIRING_YES
91 has_yes = set(args).intersection(CONDA_YES_FLAGS)
91 has_yes = set(args).intersection(CONDA_YES_FLAGS)
92 if stdin_disabled and needs_yes and not has_yes:
92 if stdin_disabled and needs_yes and not has_yes:
93 extra_args.append("--yes")
93 extra_args.append("--yes")
94
94
95 # Add --prefix to point conda installation to the current environment
95 # Add --prefix to point conda installation to the current environment
96 needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
96 needs_prefix = command in CONDA_COMMANDS_REQUIRING_PREFIX
97 has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
97 has_prefix = set(args).intersection(CONDA_ENV_FLAGS)
98 if needs_prefix and not has_prefix:
98 if needs_prefix and not has_prefix:
99 extra_args.extend(["--prefix", sys.prefix])
99 extra_args.extend(["--prefix", sys.prefix])
100
100
101 self.shell.system(' '.join([conda, command] + extra_args + args))
101 self.shell.system(' '.join([conda, command] + extra_args + args))
102 print("\nNote: you may need to restart the kernel to use updated packages.")
102 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