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

时间:2015-10-22 19:42:12

标签: python python-3.x subprocess python-3.5

Python 3.5引入了run() function in the subprocess module作为新推荐的高级子进程调用方法。

三个较旧的(可用since Python 2.5 / 2.7)高级API函数中有check_call()check_call()

Python 3.5 documentation claims
  

[...]相当于:

run(..., check=True)

文档还警告不要将subprocess.PIPE stdoutstderr传递给check_call()

  

注意

     

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

由于它是“等效的”,此警告是否也适用于run(..., check=True),即

subprocess.run(..., stdout=subprocess.PIPE, check=True)

subprocess.run(..., stderr=subprocess.PIPE, check=True)

也要避免吗? (documentation of run()没有提到这个警告。)

1 个答案:

答案 0 :(得分:8)

  

将check = True与stdout = PIPE结合使用是否安全?

不应将stdout=PIPE用作subprocess.check_call(或subprocess.call)的参数的原因是这些实用程序函数不处理进程可能接收/生成的任何输入和输出。如果您希望处理输出,则需要(在subprocess.run实施之前)使用subprocess.check_output,它专门处理输出,在its own documentation中,表示与run(..., check=True, stdout=PIPE).stdout的等效性。这清楚地表明subprocess.run(...,check=True,stdout=PIPE)是有效的。