maihabunash
maihabunash

Reputation: 1702

python + run system command with variables

I need to run system command from python

I have python - version - Python 2.4.3

I try the following , in this example ls -ltr | grep Aug

#!/usr/bin/python


import commands


Month = "Aug"
status,output = commands.getstatusoutput(" ls -ltr | grep Month "  )
print output

how to insert the Month variable in the command ?

so grep will do that

  | grep Aug

I try this also

status,output = commands.getstatusoutput( " ls -ltr | grep {} ".format(Month) )

but I get the following error

Traceback (most recent call last):
   File "./stamm.py", line 14, in ?
    status,output = commands.getstatusoutput( " ls -ltr | grep {}     ".format(Month) )
AttributeError: 'str' object has no attribute 'format'

Upvotes: 0

Views: 6485

Answers (2)

jfs
jfs

Reputation: 414875

You don't need to run the shell, there is subprocess module in Python 2.4:

#!/usr/bin/env python
from subprocess import Popen, PIPE

Month = "Aug"
grep = Popen(['grep', Month], stdin=PIPE, stdout=PIPE)
ls = Popen(['ls', '-ltr'], stdout=grep.stdin)
output = grep.communicate()[0]
statuses = [ls.wait(), grep.returncode]

See How do I use subprocess.Popen to connect multiple processes by pipes?

Note: you could implement it in pure Python:

#!/usr/bin/env python
import os
from datetime import datetime

def month(filename):
    return datetime.fromtimestamp(os.path.getmtime(filename)).month

Aug = 8
files = [f for f in os.listdir('.') if month(f) == Aug] 
print(files)

See also, How do you get a directory listing sorted by creation date in python?

Upvotes: 0

heinst
heinst

Reputation: 8786

import commands


Month = "Aug"
status,output = commands.getstatusoutput(" ls -ltr | grep '" + Month + "'")
print output

Or a couple other possibilites are:

status,output = commands.getstatusoutput("ls -ltr | grep '%s'" % Month)

or

status,output = commands.getstatusoutput(" ls -ltr | grep \"" + Month + "\"")

Upvotes: 6

Related Questions