Python 子进程看不到外部函数

问题描述 投票:0回答:1

我们正在开发一个 python 包。无论听起来多么愚蠢,我们都希望 Node.js 应用程序成为程序包的一部分(这将是 CLI 中的选项之一)。为了顺利分发它,我们希望包自动安装node.js。 我尝试了

nodejs-bin
包,但它似乎很旧并且不再工作了。 我们的想法是使用 Python
subprocess
库来做到这一点。

Node.js 网站说应该这样安装

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 22

第一部分完成没有问题(我尝试通过终端和子进程安装它)。但由于某种原因 subprocess.run 看不到 nvm

import subprocess
subprocess.run(['nvm'])
    subprocess.run(["nvm"])
  File "/usr/lib/python3.11/subprocess.py", line 548, in run
    with Popen(*popenargs, **kwargs) as process:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/subprocess.py", line 1024, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.11/subprocess.py", line 1901, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'nvm'

即使我使用

shell = True

也会发生同样的情况
import subprocess
subprocess.run(['nvm'], shell = True)
/bin/sh: 1: nvm: not found

当我只需在 Linux 的终端中输入

nvm
时,它就可以正常工作。 即使不推荐此解决方案,我也想知道子进程在后台如何工作以及为什么这不起作用

python subprocess
1个回答
0
投票

仔细阅读安装脚本,可以在

$NVM_DIR/nvm.sh
中找到nvm功能,其中
$NVM_DIR
默认设置为
$HOME/.nvm
。然后,它按顺序检查以下每个 shell 启动文件,并将
source $NVM_DIR/nvm.sh
添加到第一个找到的文件中:
$PROFILE
(如果设置)、
~/.profile
~/.bashrc
~/.bash_profile
~/.zprofile
 ~/.zshrc

要使其在 Python 中工作,

subprocess.run('source "${NVM_DIR:-$HOME/.nvm}/nvm.sh" && nvm', shell=True)
应该按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.