Skip to content
Search

Python:subprocess

lastmod 2022-10-11created 2015-04-1711 edits

Use the os.system

With this method, the program's exit code1 is returned as the return value.

import os
print os.system('example.exe')

Use the os.popen

The os.popen series appeared in python 2.0, and as of 2.6 it is recommended to replace it with subprocess's popen. subprocess appeared in version 2.4.

import os

def execute(cmd):
    std_in, std_out, std_err = os.popen3(cmd)
    return std_out, std_err

cmd = "ls -l"

std_out, std_err = execute(cmd)
for line in std_out.readlines():
    print line

Use the subprocess

import subprocess

def execute(cmd) :
    fd = subprocess.Popen(cmd, shell=True,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
    return fd.stdout, fd.stderr

cmd = "ls -l"

std_out, std_err = execute(cmd)
for line in std_out.readlines():
    print line

See also

Favorite site

References


  1. The $? value in Bash. ↩

author Zer0 sitemap