python + 运行 带变量的系统命令

python + run system command with variables

我需要 运行 来自 python 的系统命令

我有 python - 版本 - Python 2.4.3

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

#!/usr/bin/python


import commands


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

如何在命令中插入月份变量?

所以 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'
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 + "\"")

您不需要 运行 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?