Skip to content Skip to sidebar Skip to footer

How Can I Use A Piped String Of Commands With Python Subprocess Module?

I want to partition a new, blank disk using a Python script on Ubuntu. In a bash script or from the command line, this would do the job: $echo -e 'n\np\n1\n\n\nw\n' | sudo fdisk /d

Solution 1:

The 'batteries included' pipes module may be what you are looking for. Doug Hellman has a nice write-up on how to use it to get what you want.

Solution 2:

You can't pass a complex command string to the Popen() function. It takes a list as the first argument. The shlex module, particularly the split() function, will help you a lot, and the subprocess documentation has some examples that use it.

So you'd want something like:

import shlex, subprocess
command_line = 'echo -e "n\np\n1\n\n\nw\n"| sudo fdisk /dev/X'
args = shlex.split(command_line)
p = subprocess.Popen(args) # Success!

Solution 3:

You have to use two pipes actually, the input of the second pipe would be the output of the first one, so here's what to do:

 p=subprocess.Popen(['printf','n\np\n1\n\n\nw\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 p1=subprocess.Popen(['fdisk','/dev/X'],stdin=p.stdout, stderr=subprocess.PIPE, stdout= subprocess.PIPE).wait()

Bonus: notice the wait() , this way your script will wait for the fdisk to finish.

Post a Comment for "How Can I Use A Piped String Of Commands With Python Subprocess Module?"