How to call external command with Python?

Asked

Viewed 8,272 times

4

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

3 answers

3


And very simple:

import os
os.system("ls")

1

You can also use subprocess

import subprocess

subprocess.call('ls', shell = True)

0

I do so, I believe it is a pytonic 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.