How can I use a command chain with a Python subprocess module?

I want to split a new empty disk using a Python script on Ubuntu.

In a bash script or from the command line, this will do the job:

$echo -e "n\np\n1\n\n\nw\n" | sudo fdisk /dev/X 

where X is the hard drive.

I tried porting this to a Python script using the subprocess module as follows:

 p = subprocess.Popen(cmdString, stdout=subprocess.PIPE, \ close_fds=False, stderr=subprocess.PIPE,shell=True) stdoutAndErr = p.communicate() 

where cmdString is the same line of "echo -e ..." above.

This does not work. The output is just fdisk printing the command parameters, so he clearly doesn't like the fact that I'm sending it.

What is wrong with the above simple approach to life?

+1
python subprocess ubuntu
source share
3 answers

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

0
source share

You cannot pass a complex command line to the Popen () function. It takes a list as the first argument. The shlex module, especially the split () function, will help you a lot, and subprocess has a few examples that use it.

So you need 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! 
0
source share

You should actually use two pipes, the input of the second channel will be the output of the first, so here is 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: pay attention to wait (), so your script will wait for fdisk to complete.

0
source share

All Articles