0

I was wondering if there is a command that can be run in Python REPL and is equivalent to

python -m spacy download en_core_web_sm

which is run in a bash shell?

Thanks.

a_guest
  • 34,165
  • 12
  • 64
  • 118
Tim
  • 1
  • 141
  • 372
  • 590
  • 4
    https://docs.python.org/3/using/cmdline.html#cmdoption-m - Is the yellow section what you need? https://docs.python.org/3/library/runpy.html#runpy.run_module – Caramiriel Mar 30 '20 at 12:50
  • @Caramiriel: Seems like that's an answer, with just a bit of elaboration. Better than running subprocesses. – ShadowRanger Mar 30 '20 at 13:36
  • @ShadowRanger I'm curious why you think using `runpy` is superior to running subprocesses. Could you elaborate? How would you use it for the given use case? – a_guest Mar 30 '20 at 13:47
  • 1
    @a_guest, ..."better" in that there's far less startup overhead, for one -- you're using the existing Python interpreter with its existing module cache. But there's the downside that a `__main__` will often think it can call `sys.exit()` safely, so you'd want to `fork()` to guard against that if the behavior of the specific code being called isn't known not to do that. – Charles Duffy Mar 30 '20 at 13:59
  • @CharlesDuffy Unless you have complete knowledge about what a module does, I think it's safest to use a subprocess. The [pip docs](https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program) have a section that explains why the only fully supported way of invoking `pip` from within a program is to use `subprocess`. – a_guest Mar 30 '20 at 14:13

1 Answers1

3

You can use subprocess.run:

import subprocess
import sys

subprocess.run([sys.executable, '-m', 'spacy', 'download', 'en_core_web_sm'], check=True)
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • Thanks. My purpose is to make the installation affect the current python installation. There can be multiple python installations in an OS. For example, I am installing Python packages and other stuffs from the Python installation in R, not in the Python installation in my OS. Your way works. I now can't create a new post. I was wondering if you know how to do the same as `pip install lxml` but from within a Python REPL session? – Tim Mar 30 '20 at 21:35
  • @Tim You can use it similar via the `-m` switch: `python -m pip install xml` and then translate this to a `subprocess.run` call. There's a [question on SO](https://stackoverflow.com/a/50255019/3767239) as well as a detailed explanation from the [pip docs](https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program). – a_guest Mar 31 '20 at 11:28