简体   繁体   English

如何在Python中的subprocess.Popen中运行awk -F \''{print $ 2}'?

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

I need to run a shell command inside subprocess.Popen in Python. 我需要在Python中的subprocess.Popen中运行一个shell命令。

The command is: $ virsh dumpxml server1 | 命令是:$ virsh dumpxml server1 | grep 'source file' | grep'源文件'| awk -F\\' '{print $2}' awk -F \\''{print $ 2}'

The output is: /vms/onion.qcow2 输出为:/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. 1)命令在一个循环中,你看到'server1',它是一个具有服务器名称的变量。

2) Python is complaining about KeyError: 'print $2' 2)Python抱怨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. 提前致谢。

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 虽然可以直接从python使用libvirt,但你的问题是{是格式字符串,并且在你的awk脚本中包围print $2 ,所以你必须逃避那些大括号

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM