Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中带子流程的Shell管道_Python_Shell_Subprocess_Pipe - Fatal编程技术网

Python中带子流程的Shell管道

Python中带子流程的Shell管道,python,shell,subprocess,pipe,Python,Shell,Subprocess,Pipe,在使用子流程调用Python中的shell命令时,我阅读了在StackOverflow上找到的每个线程,但我找不到适用于以下情况的答案: 我想从Python中执行以下操作: 运行shell命令命令\u 1。在变量result\u 1中收集输出 壳管result_1进入命令_2并在result_2上收集输出。换句话说,使用我在前面步骤中运行command\u 1时获得的结果运行command\u 1 将相同的管道result_1导入第三个命令command_3,并在result_3中收集结果 到目

在使用
子流程调用Python中的shell命令时,我阅读了在StackOverflow上找到的每个线程,但我找不到适用于以下情况的答案:

我想从Python中执行以下操作:

  • 运行shell命令
    命令\u 1
    。在变量
    result\u 1中收集输出

  • 壳管
    result_1
    进入
    命令_2
    并在
    result_2
    上收集输出。换句话说,使用我在前面步骤中运行
    command\u 1
    时获得的结果运行
    command\u 1

  • 将相同的管道
    result_1
    导入第三个命令
    command_3
    ,并在
    result_3
    中收集结果

  • 到目前为止,我已经尝试:

    p = subprocess.Popen(command_1, stdout=subprocess.PIPE, shell=True)
    
    result_1 = p.stdout.read();
    
    p = subprocess.Popen("echo " + result_1 + ' | ' + 
    command_2, stdout=subprocess.PIPE, shell=True)
    
    result_2 = p.stdout.read();
    
    原因似乎是
    “echo”+result_1
    没有模拟获取管道命令输出的过程

    使用子流程是否可以实现这一点?如果是,如何做?

    您可以做:

    pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE)
    pipe.stdin.write(result_1)
    pipe.communicate()
    

    而不是带管道的行。

    有关正确的方法,请参阅。谢谢@SvenMarnach,这是否仍然允许我在Python变量中收集第一个命令的输出?这看起来很棒。如果我想将
    result\u 1
    再次传输到另一个命令,上述内容将如何更改?此时
    result\u 1
    是一个字符串。您应该能够使用新命令重复相同的3行。