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

2019-06-24 02:48发布

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条回答
你好瞎i
2楼-- · 2019-06-24 03:29

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]
查看更多
登录 后发表回答