GreenTeaTech GreenTeaTech - 23 days ago 8
Python Question

How to run awk -F\' '{print $2}' inside subprocess.Popen in Python?

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.

Answer

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]