How to run awk -F\\' '{print $2}' insi

2019-06-24 02:40发布

问题:

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

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

The output is: /vms/onion.qcow2

I'm having two challenges with the above command:

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

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]

Thanks in advance.

回答1:

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]