Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what is the best way to execute a local Linux command stored in a string?

Tags:

python

In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the Linux command and any caught errors to a common log file?

String logfile = “/dev/log”
String cmd = “ls”
#try
  #execute cmd sending output to >> logfile
#catch sending caught error to >> logfile 
like image 557
Chris Avatar asked Sep 08 '09 14:09

Chris


1 Answers

Using the subprocess module is the correct way to do it:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
logfile.write(output)
logfile.close()

EDIT subprocess expects the commands as a list so to run "ls -l" you need to do this:

output, error = subprocess.Popen(
                    ["ls", "-l"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()

To generalize it a little bit.

command = "ls -la"
output, error = subprocess.Popen(
                    command.split(' '), stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()

Alternately you can do this, the output will go directly to the logfile so the output variable will be empty in this case:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=logfile,
                    stderr=subprocess.PIPE).communicate()
like image 91
Nadia Alramli Avatar answered Sep 20 '22 19:09

Nadia Alramli