如何在subprocess.Popen中的Python中运行awk -F \''{print $ 2}'? [英] How to run awk -F\' '{print $2}' inside subprocess.Popen in Python?

查看:443
本文介绍了如何在subprocess.Popen中的Python中运行awk -F \''{print $ 2}'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在subprocess.Popen中运行一个shell命令.

I need to run a shell command inside subprocess.Popen in Python.

命令是: $ virsh dumpxml服务器1 | grep源文件" | awk -F \''{print $ 2}'

The command is: $ virsh dumpxml server1 | grep 'source file' | awk -F\' '{print $2}'

输出为: /vms/onion.qcow2

The output is: /vms/onion.qcow2

上述命令给我带来了两个挑战:

I'm having two challenges with the above command:

1)该命令位于循环内,在看到"server1"的地方,它是一个具有服务器名称的变量.

1) The command is inside a loop, and where you see 'server1', it is a variable that will have a server name.

2)Python在抱怨KeyError:'print $ 2'

2) Python is complaining about KeyError: 'print $2'

这是我到目前为止所拥有的:

Here is what I have so far:

proc = subprocess.Popen(["virsh dumpxml {0} | grep 'source file' | awk -F\' '{print $2}'".format(vm)], stdout=subprocess.PIPE, shell=True)

stdout = proc.communicate()[0]

谢谢.

推荐答案

虽然可以直接从python使用libvirt,但是您的问题是{是格式字符串,并且在awk脚本中将print $2括起来好吧,所以您必须避开像这样的大括号

While it's possible use libvirt directly from python, your problem is that { is the format string, and surrounds print $2 in your awk script as well, so you have to escape those braces like

proc = subprocess.Popen(["virsh dumpxml {0} | grep 'source file' | awk -F\\' '{{print $2}}'".format(vm)], stdout=subprocess.PIPE, shell=True)
stdout = proc.communicate()[0]

这篇关于如何在subprocess.Popen中的Python中运行awk -F \''{print $ 2}'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆