UNIX commands
eharetea

Use the commands module for unix commands.

Triggering UNIX commands in Python.

Date Created:Friday December 29th, 2006 03:41 AM
Date Modified:Friday August 01st, 2008 02:08 AM

# use commands module for unix commands

>>> import commands
>>> commands.getstatusoutput('ls -la')

>>> s = commands.getstatusoutput
>>> s('ls -ls')
>>> for x in s('ls')[1].replace('\n',' '):
...     print x


# pipes module and Template Object:
# uses the tr unix command to capitalize text

>>> import pipes
>>> t=pipes.Template()
# the append Template object appends a new action at the end
# the first argument must be a bourne shell command
# the second argument is saying read as standard input, write as standard output
>>> t.append('tr a-z A-Z', '--')
>>> f=t.open('readme.txt', 'w' )
>>> f.write('hello world')
>>> f.close()
>>> open('readme.txt').read()
'HELLO WORLD'


# uses prepend instead of append, changing the unix pipe order

import pipes
t=pipes.Template()
t.prepend('tr a-z A-Z', '--')
f=t.open('readme.txt', 'w' )
f.write('hello world')
f.close()
print open('readme.txt').read()

# used to copy a file:

import pipes
t=pipes.Template()
t.copy('readme.txt', 'readme_copy.txt')
print open('readme_copy.txt').read()

# same as:

from commands import getstatusoutput
getstatusoutput('cp readme.txt readme_copy.txt')
print open('readme_copy.txt').read()