Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
GreenTeaTech Avatar asked Aug 09 '15 02:08

GreenTeaTech


People also ask

How subprocess popen works in Python?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

What is the difference between subprocess run and Popen?

The main difference is that subprocess. run executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess. communicate yourself to pass and receive data to your process.

What are Subprocesses in Python?

Subprocess in Python is a module used to run new codes and applications by creating new processes. It lets you start new applications right from the Python program you are currently writing. So, if you want to run external programs from a git repository or codes from C or C++ programs, you can use subprocess in Python.


1 Answers

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]
like image 70
Eric Renouf Avatar answered Sep 16 '22 18:09

Eric Renouf