Python Script execute commands in Terminal

PythonTerminal

Python Problem Overview


I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.

For example: the script will be:

command 'ls -l'

It will out the result of running that command in the terminal

Python Solutions


Solution 1 - Python

There are several ways to do this:

A simple way is using the os module:

import os
os.system("ls -l")

More complex things can be achieved with the subprocess module: for example:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

Solution 2 - Python

I prefer usage of subprocess module:

from subprocess import call
call(["ls", "-l"])

Reason is that if you want to pass some variable in the script this gives very easy way for example take the following part of the code

abc = a.c
call(["vim", abc])

Solution 3 - Python

Solution 4 - Python

import os
os.system("echo 'hello world'")

This should work. I do not know how to print the output into the python Shell.

Solution 5 - Python

You should also look into commands.getstatusoutput

This returns a tuple of length 2.. The first is the return integer (0 - when the commands is successful) second is the whole output as will be shown in the terminal.

For ls

import commands
s = commands.getstatusoutput('ls')
print s
>> (0, 'file_1\nfile_2\nfile_3')
s[1].split("\n")
>> ['file_1', 'file_2', 'file_3']

Solution 6 - Python

for python3 use subprocess

import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)

You can also check for errors:

import subprocess
s = subprocess.getstatusoutput('ls')
if s[0] == 0:
    print(s[1])
else:
    print('Custom Error {}'.format(s[1]))


# >>> Applications
# >>> Desktop
# >>> Documents
# >>> Downloads
# >>> Library
# >>> Movies
# >>> Music
# >>> Pictures
import subprocess
s = subprocess.getstatusoutput('lr')
if s[0] == 0:
    print(s[1])
else:
    print('Custom Error: {}'.format(s[1]))

# >>> Custom Error: /bin/sh: lr: command not found

Solution 7 - Python

In python3 the standard way is to use subprocess.run

res = subprocess.run(['ls', '-l'], capture_output=True)
print(res.stdout)

Solution 8 - Python

The os.popen() is pretty simply to use, but it has been deprecated since Python 2.6. You should use the subprocess module instead.

Read here: https://stackoverflow.com/questions/2339469/reading-a-os-popencommand-into-a-string/16266645#16266645

Solution 9 - Python

Jupyter

In a jupyter notebook you can use the magic function !

!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable

ipython

To execute this as a .py script you would need to use ipython

files = get_ipython().getoutput('ls -a /data/dir/')

execute script

$ ipython my_script.py

Solution 10 - Python

  • Running: subprocess.run
  • Output: subprocess.PIPE
  • Error: raise RuntimeError

#! /usr/bin/env python3
import subprocess


def runCommand (command):
	output=subprocess.run(
		command,
		stdout=subprocess.PIPE,
		stderr=subprocess.PIPE)

	if output.returncode != 0:
		raise RuntimeError(
			output.stderr.decode("utf-8"))

	return output


output = runCommand ([command, arguments])
print (output.stdout.decode("utf-8"))

Solution 11 - Python

You could import the 'os' module and use it like this :

import os
os.system('#DesiredAction')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAliView Question on Stackoverflow
Solution 1 - PythonUku LoskitView Answer on Stackoverflow
Solution 2 - PythonKevin PandyaView Answer on Stackoverflow
Solution 3 - PythonpyfuncView Answer on Stackoverflow
Solution 4 - PythonMr_pzling_PieView Answer on Stackoverflow
Solution 5 - PythonminochaView Answer on Stackoverflow
Solution 6 - PythonAvi AvidanView Answer on Stackoverflow
Solution 7 - PythonRuggero TurraView Answer on Stackoverflow
Solution 8 - PythonPaolo RovelliView Answer on Stackoverflow
Solution 9 - PythonRickView Answer on Stackoverflow
Solution 10 - PythonAlberto Salvia NovellaView Answer on Stackoverflow
Solution 11 - PythonKobe KeirouzView Answer on Stackoverflow