How to call external command with Python?

4

How can I call an external command in Python, as if it were executed in the Unix shell or at the Windows prompt?

    
asked by anonymous 21.08.2014 / 17:50

3 answers

3

And very simple:

import os
os.system("ls")
    
21.08.2014 / 17:52
1

You can also use subprocess

import subprocess

subprocess.call('ls', shell = True)
    
22.08.2014 / 18:08
0

I do this, I think it's a pythonic way:

from subprocess import Popen, PIPE
class Cmd(object):
   def __init__(self, cmd):
       self.cmd = cmd
   def __call__(self, *args):
       command = '%s %s' %(self.cmd, ' '.join(args))
       result = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
       return result.communicate()
class Sh(object):
    """Ao ser instanciada, executa um metodo dinamico
    cujo nome serah executado como um comando. Os argumentos
    passados para o metodo serao passados ao comando.

    Retorna uma tupla contendo resultado do comando e saida de erro

    Exemplo:
    shell = Sh()
    shell.ls("/")

    Ver http://www.python.org.br/wiki/PythonNoLugarDeShellScript
    """
    def __getattr__(self, attribute):
        return Cmd(attribute)
    
29.08.2014 / 00:29