Python脚本未安装npm包



我在python 中有这段代码

import subprocess
subprocess.Popen(["npm", "install", "express"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

然而,它似乎不起作用,它没有安装任何东西。当我看到错误时,它告诉我npm命令的正确用法。

请记住,这是在Ubuntu 18.04 上的Python 3.8.8上

import subprocess
proc = subprocess.Popen(["npm", "install", "express"])

我在Ubuntu 20.04上测试了这个,它按预期运行了这个命令。

唯一的问题是它在NPM过程中被卡住了,我不得不按取消键退出这个过程。

不要使用subprocess,试着像这样使用os

import os
os.system("npm install express")
os.system("echo You can run commands from terminal using os.")

在我的第一篇文章destroyer22719上评论道:

嗨!这对我来说是有效的,但我可以问一下,这个是如何工作的,而另一个不是吗?我相信子流程的工作对我来说很重要。

我想说,我从未学会如何使用子流程,所以我不知道它是如何工作的。但是,环顾四周,我想我找到了一个解决方案。

一周前,我在最新版本的ubuntu(python 3.8.10(和我的windows 10(python 3.9(上进行了测试,它在windows 10上失败,但在ubuntu上有效。

Ubuntu版本:

import subprocess
from threading import Thread
def package():
subprocess.Popen(["npm install express"], shell=True)
Thread(target=package).start()
print("This text will print if the command is finished or not.")

这是适用于windows的:

import subprocess
from threading import Thread
def package():
subprocess.Popen(["npm", "install", "express"], shell=True)
Thread(target=package).start()
print("This text will print if the command is finished or not.")

threading是导入的,因为当您运行进程时,它不会停止,所以我使用Thread()来绕过这一点。

最新更新