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" |开发者_StackOverflow sudo fdisk /dev/X
where X is the HDD in question.
I have tried to port this into 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 just the same "echo -e ..."
string above.
This doesn't work though. Output is just fdisk
printing out the command options, so it clearly doesn't like what I am sending it.
What's wrong with the above simple approach to life?
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.
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!
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.
精彩评论