【问题标题】:String substitution into a subprocess call字符串替换到子进程调用
【发布时间】:2014-02-28 07:04:11
【问题描述】:

如何在 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

【问题讨论】:

  • 你只需要逃避它:timeformat= "%%s"
  • 它的错误类似于未知命令'timeformat'

标签: python python-2.7 subprocess


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您收到的错误消息非常解释:您有四个 %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)
    

    【讨论】:

    • 这里的时间格式是将日期和时间转换成需要的格式。它不是需要传递值的变量……如何在这种情况下将日期时间转换为所需的格式
    • 啊好吧,我明白了!我认为伯尼对您的问题的评论为您提供了解决方案:%s 作为timeformat 值必须被转义。
    • 好吧,print '%s %s %s' % ('aa', 'bb') 返回您遇到的错误,而 print '%s %%s %s' % ('aa', 'bb') 没有。这也适用于您的示例。这不适合你吗?
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2017-12-06
    • 2019-08-25
    • 2019-04-15
    • 2017-04-24
    • 2012-08-09
    • 2014-10-12
    • 2016-12-24
    相关资源
    最近更新 更多