155

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

Ali
  • 4,311
  • 11
  • 44
  • 49
  • I guess by "terminal" you mean "as in the command line", see https://superuser.com/questions/144666/what-is-the-difference-between-shell-console-and-terminal – Ruggero Turra May 11 '21 at 23:17

11 Answers11

270

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]
Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • 58
    I don't want to downvote you but. You should use subprocess for everything. It's way safer. subprocess.call() will get you a nice interface in order to replace the simple call form. – Jorge Vargas Mar 24 '11 at 20:35
  • Thanks for that answer mate. Will be using python for my first application on Ubuntu desktop, this will really help me. – LinuxBill Jan 16 '13 at 10:55
  • 3
    How can I get the complete response of a command, `os.system("nslookup gmail.com")` only returns the last line `0`, but I want to get the full response. – Parthapratim Neog Nov 29 '15 at 10:06
  • 7
    @JorgeVargas Can you help me understand why subprocess should be used for everything? Why is it safer? – Soutzikevich Feb 22 '19 at 19:34
  • I've done this with more complex subprocess and threaded management before, I wasn't aware it was great for simple one-off's also, thanks. – Jamie Nicholl-Shelley Oct 28 '22 at 13:37
62

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])
Kevin Pandya
  • 1,036
  • 1
  • 9
  • 12
  • 2
    Worked well for me opening up a picture with extra parameters `call(["eog", "1breeproposal.png", "-f"])` – Josh Jul 01 '20 at 07:59
10
import os
os.system("echo 'hello world'")

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

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Mr_pzling_Pie
  • 160
  • 1
  • 12
8

In fact any question on subprocess will be a good read

Community
  • 1
  • 1
pyfunc
  • 65,343
  • 15
  • 148
  • 136
6

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
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
Avi Avidan
  • 866
  • 8
  • 18
5

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']
Neuron
  • 5,141
  • 5
  • 38
  • 59
minocha
  • 1,043
  • 1
  • 12
  • 26
3

In python3 the standard way is to use subprocess.run

res = subprocess.run(['ls', '-l'], capture_output=True)
print(res.stdout)
Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141
1

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: reading a os.popen(command) into a string

Community
  • 1
  • 1
Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
1

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
Rick
  • 2,080
  • 14
  • 27
0

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

import os
os.system('#DesiredAction')
0
  • 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"))