python +带变量的run系统命令

时间:2015-08-05 12:18:53

标签: python linux python-2.4

我需要从python

运行系统命令

我有python - 版本 - Python 2.4.3

我尝试以下操作,在此示例中 ls -ltr | grep Aug

#!/usr/bin/python


import commands


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

如何在命令中插入Month变量?

所以grep会这样做

  | grep Aug

我也尝试了这个

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

但是我收到以下错误

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'

2 个答案:

答案 0 :(得分:4)

import commands


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

或者其他几个可能性是:

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

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

答案 1 :(得分:0)

您不需要运行shell,Python 2.4中有subprocess模块:

#!/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]

请参阅How do I use subprocess.Popen to connect multiple processes by pipes?

注意:您可以在纯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)

另见How do you get a directory listing sorted by creation date in python?