流水线命令在python结构中不起作用

时间:2018-01-12 00:01:23

标签: python bash pipe fabric pipelining

我试图管道多个bash命令从列出图像名称的命令输出中提取图像名称,但它不起作用 - 它会吐出一团文本,一步一步地执行的工作原理。

使用管道的代码:

@task
def update():
    image_name = sudo('/os-updater --list | grep X86-64_ | sed "s/XXX/UEK4/" | tail -1')
    print("IMAGE NAME: "+image_name)

输出:

user@system:host-updater$ ./hu -R host-name update
[host-name] Executing task 'update'
[host-name] sudo: /os-updater --list | grep X86-64_ | sed "s/XXX/UEK4/" | tail -1
[host-name] out: 2018-01-11 23:33:28,628 INFO ==> os-updater 1.3.3 started
[host-name] out: 2018-01-11 23:33:28,629 INFO --listsnapshots:True
[host-name] out: 2018-01-11 23:33:28,705 INFO Exit 0
[host-name] out:   X86-64_20171201.01_UEK4
[host-name] out: 

IMAGE NAME: 2018-01-11 23:33:28,628 INFO ==> os-updater 1.3.3 started
2018-01-11 23:33:28,629 INFO --listsnapshots:True
2018-01-11 23:33:28,705 INFO Exit 0
  X86-64_20171201.01_UEK4

Done.

没有pipleine的代码:

@task
def update():
    image_list = sudo("/os-updater --list")
    out = image_list.stdout
    for line in out.splitlines():
        if 'X86-64_' in line:
            image_name = line.replace("XXX", "UEK4").strip()

    print("IMAGE NAME: " + image_name)

输出:

user@system:host-updater$ ./hu -R host-name update
[host-name] Executing task 'update'
[host-name] sudo: /os-updater --list
[host-name] out: 2018-01-11 23:36:11,752 INFO ==> os-updater 1.3.3 started
[host-name] out: 2018-01-11 23:36:11,753 INFO --listsnapshots:True
[host-name] out: 2018-01-11 23:36:11,847 INFO Exit 0
[host-name] out: Snapshots:
[host-name] out:   X86-64_20171101.01_XXX
[host-name] out:   X86-64_20171201.01_XXX
[host-name] out: Kernel trains: (XXX above)
[host-name] out:   UEK4
[host-name] out:   STOCK
[host-name] out: 

IMAGE NAME: X86-64_20171201.01_UEK4

Done.

我不明白为什么第二种方式(字面意思是一步一步地没有管道)工作但不是第一种方式返回大量带有图像名称的文本。 我尝试了很多东西:

image_name = sudo('/opt/os-updater/bin/os-updater --list | grep X86-64_OL7_ | sed "s/XXX/UEK4/" | tail -1').stdout.strip() 

然后使用结构隐藏选项# with hide('output','running','warnings'):运行命令。它都不起作用。 流水线操作并不常见,这很奇怪。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

管道是shell语法元素。你需要在shell中运行它:

sudo("/os-updater --list | sed -n '/X86-64_/s/XXX/UEK4/p' | tail -1", shell=True)

PS:我可以自由地将grepsed命令合并为一个。