简体   繁体   English

Python 脚本未安装 npm 包

[英]Python script not installing npm package

I have this code here in python我在 python 中有这个代码

import subprocess

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

however it doesn't seem to work, it doesn't install anything.但是它似乎不起作用,它没有安装任何东西。 When I look at the error it tells me the proper usage of the npm command.当我查看错误时,它告诉我 npm 命令的正确用法。

Keep in mind this is on Python 3.8.8 on Ubuntu 18.04请记住,这是在 Ubuntu 18.04 上的 Python 3.8.8 上

Instead of using subprocess , Try using os like this:而不是使用subprocess ,尝试使用os像这样:

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

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

I tested this on Ubuntu 20.04 and it ran the command as expected.我在 Ubuntu 20.04 上对此进行了测试,它按预期运行了命令。

Only thing is that it gets stuck in the NPM process and I've had to press cancel to exit the process.唯一的问题是它卡在 NPM 进程中,我不得不按取消退出进程。

On my first post destroyer22719 commented:在我的第一篇文章中,destroy22719 评论道:

Hi there!你好呀! This worked for me, however may I ask how this one works while the other one doesn't?这对我有用,但是我可以问这个是如何工作的,而另一个则不是吗? I believe it's important for me that subprocess works.我相信子流程的工作对我来说很重要。

I would like to say, I never learned how to use subprocess, so I wouldn't know how it works or anything.我想说,我从来没有学过如何使用子流程,所以我不知道它是如何工作的或任何事情。 But, with a little bit of looking around I think I found a solution.但是,稍微环顾四周,我想我找到了解决方案。

I tested on the latest version of ubuntu as of a week ago (python 3.8.10) and on my windows 10 (python 3.9) and it fails on windows 10 but works on ubuntu.一周前,我在最新版本的 ubuntu(python 3.8.10)和我的 windows 10(python 3.9)上进行了测试,它在 windows 10 上失败,但在 ubuntu 上工作。

Ubuntu Version: 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.")

This is the one that works on windows:这是在 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 is imported because when you run the process it doesn't just stop, so I used Thread() to get around that.导入threading是因为当您运行该进程时,它不会停止,所以我使用Thread()来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM