0

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'
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
maihabunash
  • 1,632
  • 9
  • 34
  • 60

2 Answers2

6
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 + "\"")
heinst
  • 8,520
  • 7
  • 41
  • 77
  • I cant use the import subprocess because my python version ( File "/usr/lib/python2.4/subprocess.py", line 550, in __init__ errread, errwrite) ) – maihabunash Aug 05 '15 at 12:25
  • 1
    You _could_ use single quotes on that grep argument, since it's a fixed string. Double quotes in the shell are needed when you want parameter expansion, but that's not needed here. Another possibility is `"ls -ltr | grep '%s'" % Month`. – PM 2Ring Aug 05 '15 at 12:35
0

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?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670