在check_output中调用循环

时间:2017-03-20 07:57:17

标签: python

我正在尝试使用带有for循环的check_output传递shell命令: 例如:

 check_output("ceph osd erasure-code-profile set LRCprofile /\ "
      + "plugin=lrc /\ \n"
      + "layers='[ \n"
      for i in range (0,layers):
          + " str(''.join(lay[i])) \n "
      + "]' "
      + , shell=True)

这样命令将采用以下形式:

ceph osd erasure-code-profile set LRCprofile \
     plugin=lrc \
     layers='[
               [ "_cDD_cDD", "" ],
               [ "cDDD____", "" ],
               [ "____cDDD", "" ],
             ]'

这会发出错误。

有没有办法根据参数传递shell一个变化大小的命令?

由于

2 个答案:

答案 0 :(得分:0)

以下假设Python 3:

layers = [
    "_cDD_cDD",
    "cDDD____",
    "____cDDD"
]

layers = [e for layer in layers for e in (layer, "")]
layers = str(layers).replace("'", '"')

command = [
    "ceph", "osd",
    "erasure-code-profile", "set", "LRCprofile",
    "plugins=lrc",
    "layers='{}'".format(layers)
]

使用print(" ".join(command))打印命令返回:

ceph osd erasure-code-profile set LRCprofile plugins=lrc layers='["_cDD_cDD", "", "cDDD____", "", "____cDDD", ""]'

您应该可以直接使用command列表变量check_output

答案 1 :(得分:-1)

check_output将列表作为参数,而不是字符串。因此,您可以尝试在单独的步骤中生成命令,将其转换为列表,然后将此列表用作check_output中的参数