gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:57:19 25 4
gpt4 key购买 nike

我需要从 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 + "\"")

关于python + 运行带变量的系统命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31832334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com