我需要使用特定版本的node.js才能从python代码编译js项目。但是,版本可能会在 python 代码运行之间发生变化。
当我尝试使用 os.system 设置版本时,如下所示:
os.system(f"/bin/bash -i -c 'nvm use {node_version}'"))
控制台打印出操作成功。然而,如果我事后检查版本,我发现没有任何改变。
我也尝试在 bash 脚本中运行 python 之前设置它,都使用
nvm use
和nvm alias default
,但到目前为止还没有运气。
我怎样才能实现这个目标?我更喜欢只为 python 运行时更改版本,但只要在 python 执行的整个持续时间内使用正确的版本,也可以将版本设置为默认版本。
提前谢谢大家。
以下是如何使用 subprocess 更改 Python 脚本中的 Node.js 版本的示例:
import subprocess
# Specify the desired Node.js version
node_version = "12.18.3"
# Use subprocess to run the 'nvm use' command
cmd = f"/bin/bash -i -c 'nvm use {node_version}'"
subprocess.run(cmd, shell=True)
# Now, any subsequent commands or processes in this Python script will use the specified Node.js version.