Python script not installing npm package - python

I have this code here in 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.
Keep in mind this is on Python 3.8.8 on Ubuntu 18.04

import subprocess
proc = subprocess.Popen(["npm", "install", "express"])
I tested this on Ubuntu 20.04 and it ran the command as expected.
Only thing is that it gets stuck in the NPM process and I've had to press cancel to exit the process.

Instead of using subprocess, Try using os like this:
import os
os.system("npm install express")
os.system("echo You can run commands from terminal using os.")

On my first post destroyer22719 commented:
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 Version:
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:
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.

Related

python subprocess behaviour changed between ubuntu 20 and 22?

I upgraded my ubuntu installation to 22.04 from 18.04 yesterday. Now I notice that python virtual environment is no longer working as expect.
I use python to run a lot of tools, and hence am highly dependent on subprocess library.
However to my "horror" I notice that it changed quite a lot, even when I keep using python 3.8. Mostly I notice I can no longer interact and the output is no longer piped to the shell that executes the python script.
import subprocess
def main():
proc = subprocess.run(["echo", "test"], check=True, stdout=subprocess.PIPE)
print('-------')
print(proc.stdout)
print("FINISH")
if __name__ == "__main__":
main()
If I call this with python3.8 test.py I notice that the output isn't displayed in the shell. However it is displayed when the prints happen.
What changed and how do I fix this? So output of the subprocess is piped to the output and can be seen?
Especially since a lot of tools are just running dockers (which in turn run git/javascript programs) and having output while the process is busy is kind of useful.

running shell command in python under git-bash not working well

I am using python3 under git-bash environment, and sometimes it does not run shell command well.
#!/usr/bin/env python3
import subprocess as sp
print("hello")
print(sp.getoutput("ls -l")) # This works.
print(sp.getoutput("date")) # This hangs and cannot terminate with ctrl-c.
This does not happen when running under normal linux/bash environment.
Then I come across this one: Python not working in the command line of git bash.
I can run using "winpty python ...", however it still cannot terminate even with ctrl-c.
I take back, getoutput("date") hangs but check_output works.
You are needlessly running those commands with a shell.
Prefer this form:
print(sp.check_output(["ls", " -l"]))
print(sp.check_output(["date"]))

I would like to know how to set the time using Python in the Linux operating system

OS : Ubuntu LTS 18.04
Language : Python3
I am using Ubuntu Linux OS and I want to set the current time in Python language if the OS time is different from the current time. To set the Linux time, it was confirmed that the following system command was executed.
And the current time is reading information from a separate GPS device.
sudo date -s "2021-08-04 10:07:01"
In order to be able to execute this system command in Python, a test was conducted using the subprocess library.
import subprocess
proc = subprocess.Popen(["sudo", "date", "-s", currenttime])
However, it does not run normally. I'm guessing it's probably because you're using the sudo command. So, when I ran it except for the sudo part, "You do not have permission to execute the date command." message is output.
import subprocess
proc = subprocess.Popen(["date", "-s", currenttime])
I don't know if I'm approaching in the wrong direction. Can you give me a wise answer?
Import the subprocess library
import subprocess
Now check the output of your running cmd by storing into variable. If you want to set new data just give the whole cmd into that fn just replace the cmd from your
output = subprocess.check_output("cmd", shell=True)

Run command with sudo from a graphical Python program

I want to create a graphical python application that can execute some external programs on Linux without showing the terminal.
First, I tried to use subprocess.run() to see if it actually works, but Python 3.7.3 shows no results to the code I wrote.
import subprocess
subprocess.run(['sudo', 'apt', 'update'])
I changed it to see any results:
import subprocess
a = subprocess.run(['sudo', 'apt', 'update'])
print(a)
but it shows this result instantly:
CompletedProcess(args=['sudo', 'apt', 'update'], returncode=1)
This script will take at least 5 seconds to be finished, and it requires sudo privileges to be able to run it in the first place, so I don't think that Python shell executed this script.
Using pkexec instead of sudo fixed my issue. Thanks for everyone tried to help me especially #Charles Duffy.
Now it looks like this:
import subprocess
result = subprocess.run(['pkexec', 'apt', 'update'], stdout=subprocess.PIPE)
print(result.stdout)

How to make a python script which can logoff, shutdown, and restart a computer?

Background
I am currently in the process of teaching myself python, and I thought that it would be a very cool project to have a sort of "control center" in which I could shutdown, restart, and log off of my computer. I also want to use the subprocess module, as I have heard that the import OS module is outdated.
Current Code
def shutdown(self):
import subprocess
subprocess.call(["shutdown", "-f", "-s", "-t", "60"])
Question
What I am really asking is, is there a way (using the subprocess module) to logoff of and restart my computer?
Tech Specs
Python 2.7.3
Windows 7, 32 bit
First you have to:
import subprocess
To shutdown your Windows PC:
subprocess.call(["shutdown", "/s"])
To restart your windows PC
subprocess.call(["shutdown", "/r"])
To logout your Windows PC:
subprocess.call(["shutdown", "/l "])
To shutdown your Windows PC after 900s:
subprocess.call(["shutdown", "/s", "/t", "900"])
To abort shutting down because there is no good reason to shutdown your pc with a python script, you were just copy-pasting code from stackoverflow:
subprocess.call(["shutdown", "/a "])
I only tried these function calls in Python 3.5. First of all, I do not think this has changed since python 2.7, and second: it is 2016, so I guess you have made the switch already since asking this question.
To restart:
shutdown /r
To log off:
shutdown /l
The final code block (as requested):
Log off:
def shutdown(self):
import subprocess
subprocess.call(["shutdown", "-f", "-s", "-t", "60"])
Restart:
def shutdown(self):
import subprocess
subprocess.call(["shutdown", "-f", "-r", "-t", "60"])
If you can't get shutdown to work somehow, you can always just call the function it calls out of the USER library. You could do this via ctypes or win32api, but you can also just do this:
subprocess.call(['rundll32', 'user.exe,ExitWindowsExec')
Or you could call the higher-level shell function that the start menu uses:
subprocess.call(['rundll32', 'shell32.dll,SHExitWindowsEx 2')
(See MSDN documentation on these functions.)
I think this is probably the worst way to do it. If you want to run a command, run shutdown; if you want to use the API, use win32api. But if you've got a bizarrely screwed-up system where shutdown /r just doesn't work, it's an option.

Categories

Resources