字符串替换为子进程调用

时间:2014-02-28 07:04:11

标签: python python-2.7 subprocess

如何正确地在Python中执行此Unix命令,将给定值index, username, password替换为命令?

abc.py

import subprocess,datetime
cmd = '\./splunk search "| dbinspect index=%s |timeformat= "%s" rename state as category | stats min(earliestTime) as earliestTime max(latestTime) as latestTime sum(sizeOnDiskMB) as MB by category " -auth %s:%s | grep -v "category" | grep -v "-"' %(index, username, password)

subprocess.call(cmd, shell = True)

当我尝试执行命令时,出现错误:

TypeError: not enough arguments for format string

2 个答案:

答案 0 :(得分:0)

字符串中有四个“%s”格式描述符,(index, username, password)元组中只有三个元素。

答案 1 :(得分:0)

您得到的错误消息非常明确:您有四个%s是您的字符串,但您提供的元组中只有三个值。你可能忘记了timeformat值吗?

如果您需要重复使用相同的参数,可以使用'some text and {0}'.format(my_string)使用其他形式的字符串格式:

cmd = '\./splunk search "| dbinspect index={0} |timeformat= "{1}" rename state as category | stats min(earliestTime) as earliestTime max(latestTime) as latestTime sum(sizeOnDiskMB) as MB by category " -auth {2}:{3} | grep -v "category" | grep -v "-"'.format(index, timeformat, username, password)