Wednesday, March 11, 2009

Replacing os.popen() with subprocess.Popen() in Python

In Python, you can execute shell commands using the os.popen method...but it's been deprecated in favor of a whole new command.

# The old way, which worked great!
import os
shell_command = 'date'
event = os.popen(shell_command)
stdout = event.readlines()
print stdout

# The new way, which is more powerful, but also more cumbersome.
from subprocess import Popen, PIPE, STDOUT
shell_command = 'date'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, 
    stderr=STDOUT, close_fds=True)
output = event.stdout.read()
print output

# The new way, all in one line (a bit uglier), works in Python3!
import subprocess
output = subprocess.Popen('date', stdout=subprocess.PIPE).stdout.read()
print output

No comments:

Post a Comment