subprocess.run:将check = True与stdout = PIPE结合起来是否安全?

das*_*s-g 2 python subprocess python-3.x python-3.5

Python 3.5引入了模块中run()函数subprocess作为新推荐的高级子进程调用方法.

在三个较旧的(自Python 2.5/2.7以来可用)高级API函数中check_call().在Python的3.5文档声称check_call()

[...]相当于:

run(..., check=True)
Run Code Online (Sandbox Code Playgroud)

该文件还警告说,不要通过subprocess.PIPE作为stdoutstderrcheck_call():

注意

不要使用stdout=PIPEstderr=PIPE使用此功能.子进程将阻塞它是否为管道生成足够的输出以填充OS管道缓冲区,因为没有读取管道.

由于它是"等效的",这个警告是否也适用于run(..., check=True),即应该

subprocess.run(..., stdout=subprocess.PIPE, check=True)
Run Code Online (Sandbox Code Playgroud)

subprocess.run(..., stderr=subprocess.PIPE, check=True)
Run Code Online (Sandbox Code Playgroud)

也要避免吗?(文件run()中没有提到这个警告.)

ppp*_*ery 8

将check = True与stdout = PIPE结合起来是否安全?

是.

不应该stdout=PIPEsubprocess.check_call(或subprocess.call)作为参数使用的原因是这些实用程序函数不处理进程可能接收/生成的任何输入和输出.如果你想处理输出,你需要(在subprocess.run实现之前)使用subprocess.check_output,它特别处理输出,在它自己的文档中,它表示等效run(..., check=True, stdout=PIPE).stdout.这清楚地表明这subprocess.run(...,check=True,stdout=PIPE)是有效的.