5

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.

GreenTeaTech
  • 423
  • 4
  • 7
  • 16

1 Answers1

10

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]
Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • Thank you. That makes sense, but I'm still getting an error: /bin/sh: -c: line 0: unexpected EOF while looking for matching `'' /bin/sh: -c: line 1: syntax error: unexpected end of file – GreenTeaTech Aug 09 '15 at 06:59
  • @GreenTeaTech Right you are, I had fixed this in my local attempts, but forgot to in my answer (though I have edited it to have that fix now). The problem is with the `-F\'` in awk, python is "eating" the `\` so you need to escape it – Eric Renouf Aug 09 '15 at 12:09