如何从 subproces.run() 运行 pip install 命令

How to run a pip install command from a subproces.run()

我在这篇文章中看到:making and automatic python installer 您可以使用:

subprocess.run('pip install module_name')

subprocess.run('pip install -r requirements.txt')

以这种格式单独安装模块或形成文件。但是当我 运行 这个命令时,我得到这个错误:

FileNotFoundError: [Errno 2] No such file or directory:

有没有一种方法可以 运行 这样而不必这样做:

subprocess.run(['pip', 'install', 'module_name'])

为了使其在 Linux 上运行,我使用了 shell=True 参数。在 Windows 上,它运行良好,没有它。

subprocess.run("python -m pip install -r requirements.txt", shell=True)

找到答案here

我建议你坚持subprocess.run(['pip', 'install', '-r', 'requirements.txt'])。引用 subprocess docs.

Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names).

如果您想 运行 不同系统上的脚本,避免使用 shell=True 将为您省去很多麻烦。不过,总的来说,我建议避免依赖 shell。毕竟,这就是为什么您使用 Python 而不是 Bash.