简体   繁体   English

如何在Python子进程模块中使用管道命令字符串?

[英]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. 我想在Ubuntu上使用Python脚本对新的空白磁盘进行分区。

In a bash script or from the command line, this would do the job: 在bash脚本中或从命令行中,将完成以下工作:

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

where X is the HDD in question. 其中X是所讨论的HDD。

I have tried to port this into a Python script using the subprocess module, as follows: 我尝试使用subprocess模块​​将此移植到Python脚本中,如下所示:

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. 其中, cmdString与上面的字符串"echo -e ..."相同。

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. 输出只是fdisk打印出命令选项,因此显然不喜欢我发送的内容。

What's wrong with the above simple approach to life? 上述简单的生活方法有什么问题?

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. 奖励:注意wait(),这样您的脚本将等待fdisk完成。

You can't pass a complex command string to the Popen() function. 您不能将复杂的命令字符串传递给Popen()函数。 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. shlex模块,尤其是split()函数,将为您提供很多帮助, 子流程文档中有一些使用它的示例。

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!

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. 道格·海尔曼(Doug Hellman) 撰写了一篇很好的文章,介绍如何使用它来获取所需的内容。

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

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