代码之家  ›  专栏  ›  技术社区  ›  M Leonard

将命令(带返回)回显到Popen stdin中

  •  0
  • M Leonard  · 技术社区  · 7 年前

    我想在python中运行一个fdisk函数,但返回结果使它无法运行。。。

    command = ['echo', '-e', "'o\nn\np\n1\n\n\nw'", '|', 'sudo', 'fdisk', '/dev/xvdm']
    p = subprocess.Popen(command, stdin=subprocess.PIPE, 
                                  stdout=subprocess.PIPE, 
                                  stderr=subprocess.PIPE)
    output, err = p.communicate()
    

    这将提供以下(不正确)输出: b"'o\nn\np\n1\n\n\nw' | sudo fdisk /dev/xvdm\n"

    等价物是什么?

    2 回复  |  直到 7 年前
        1
  •  2
  •   scnerd    7 年前

    为什么不直接跑 fdisk 然后自己发送输入?

    command = ['sudo', 'fdisk', '/dev/xvdm']
    p = subprocess.Popen(command, stdin=subprocess.PIPE, 
                                  stdout=subprocess.PIPE, 
                                  stderr=subprocess.PIPE)
    output, err = p.communicate(b"o\nn\np\n1\n\n\nw")
    
        2
  •  0
  •   Guillaume L.    7 年前

    不能在这样的命令中使用管道(|)。管道作为程序的参数提供(在您的示例中为“echo”)。

    scnerd为您提供了将输入文本发送到fdisk的最佳方式/答案。

    如果确实要保留管道,则应运行参数为“-c”(命令)的“bash”程序,并在参数中提供命令(包括管道):

    command = ['bash', '-c', "echo -e 'o\nn\np\n1\n\n\nw' | sudo fdisk /dev/xvdm"]
    p = subprocess.Popen(command, stdin=subprocess.PIPE, 
                         stdout=subprocess.PIPE, 
                         stderr=subprocess.PIPE)
    output, err = p.communicate()