了解子流程、POPEN和PIPE

understanding of subprocess, POPEN and PIPE

我是 python 和编程的新手,我正在尝试理解这段代码。在过去的几个小时里,我一直在阅读文档和观看有关子处理的视频,但我仍然感到困惑(我添加了一些我在网上找到的信息,以尽我所能评论代码)。

以下是我对以下代码的一些疑问:

什么时候使用子流程? 我什么时候应该使用 Popen 与更方便的子进程句柄? 管道是做什么的? close_fds 是做什么的?

基本上我需要解释这行代码

my_process=Popen(['player',my_video_File_path], stdin=PIPE, close_fds=True)

完整代码在这里:

#run UNIX commands we need to create a subprocess
from subprocess import Popen, PIPE
import os
import time
import RPi.GPIO as GPIO
my_video_file_path='/home/pi/green1.mp4'
#stdin listens for information
# PIPE connnects the stdin with stdout
#pipe, (like a pipe sending info through a tunnel from one place to another )
#STDIN (channel 0):
#Where your command draws the input from. If you don’t specify anything special this will be your keyboard input.
#STDOUT (channel 1):
#Where your command’s output is sent to. If you don’t specify anything special the output is displayed in your shell.
#to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE.
#Popen interface can be used directly with subprocess

# with pipe The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.
#If we pass everything as a string, then our command is passed to the shell;
#"On Unix, if args is a string, the string is interpreted as the name or path of the program to execute. "
my_process=Popen(['player',my_video_File_path], stdin=PIPE, close_fds=True)
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(22,GPIO.IN,pull_up_down=GPIO.PUD_UP)


while True:
    button_state=GPIO.input(17)
    button_state1=GPIO.input(22)

    if button_state==False:
        print("quite video")
        my_process.stdin.write("q")
        time.sleep(.09)

    if button_state1==False:
        print("full video")
        my_process.stdin.write("fs")
        time.sleep(5)

关于subprocess和Popen的区别,这里是python 3.5 docs的一行:

For more advanced use cases, the underlying Popen interface can be used directly. (compared to using subprocess)

所以,这意味着 subprocess 是 Popen 的包装器。

PIPE 用于让您的 python 脚本通过标准 IO 操作与子进程通信(您可以将 python 中的打印视为一种标准输出)。

因此,当您执行 my_process.stdin.write("fs") 时,您正在将此文本(或管道)发送到子进程的标准输入。然后你的子进程读取这个文本并做它需要做的任何处理。

要进一步了解子处理,请尝试将标准输入读入 python 程序以了解其工作原理。您可以按照这个 How do you read from stdin in Python? 问题来做这个练习。

此外,学习更通用的 linux 风格的管道可能是值得的。尝试通读 this article.