suprocess.run(['ls', '-la'], capture_output=True).stdout 和 suprocess.check_output(['ls', '- 有什么区别拉'])?
What is the difference between suprocess.run(['ls', '-la'], capture_output=True).stdout and suprocess.check_output(['ls', '-la'])?
我是 Python 的初学者,我似乎找不到以下两者之间的区别,
import subprocess
test1 = subprocess.run(['ls', '-la'], capture_output=True)
print(test1.stdout)
test2 = subprocess.check_output(['ls', '-la'])
print(test2)
我发现 test1 和 test2 都给我同样的东西。有什么区别?
还有两个我在用谷歌搜索时不明白的术语是 'Popen constructor' 和 'pipe'。如果您也能详细说明这两者以及它们与子流程模块的关系,将会很有帮助。
将 capture_output
参数传递给 subprocess.run
是 Python 3.7 中的新功能。
subprocess.check_output
是旧的 high-level API (docs):
Prior to Python 3.5, these three functions comprised the high level API to subprocess
. You can now use run()
in many cases, but lots of existing code calls these functions.
保留旧的 API 是为了向后兼容 - 删除它们几乎没有好处,并且需要很长的弃用期才能避免破坏现有代码。
Popen
("process open") 是较低级别 API 将被 run
、check_output
等内部使用。“Popen 构造函数”记录在案 here.
子进程pipe只是子进程API对底层操作系统提供的inter-process通信特性的抽象。例如,使用 shell ls -la | grep needle
将使用管道 |
将 ls
的标准输出连接到 grep
的标准输入。要在子进程 API 中执行类似操作,您可以在生成子进程时将特殊值 subprocess.PIPE
作为标准输出句柄传递。您可能会将管道视为一个小型 FIFO 缓冲区,它将一个进程的输出引导至另一个进程的输入。
我是 Python 的初学者,我似乎找不到以下两者之间的区别,
import subprocess
test1 = subprocess.run(['ls', '-la'], capture_output=True)
print(test1.stdout)
test2 = subprocess.check_output(['ls', '-la'])
print(test2)
我发现 test1 和 test2 都给我同样的东西。有什么区别?
还有两个我在用谷歌搜索时不明白的术语是 'Popen constructor' 和 'pipe'。如果您也能详细说明这两者以及它们与子流程模块的关系,将会很有帮助。
将 capture_output
参数传递给 subprocess.run
是 Python 3.7 中的新功能。
subprocess.check_output
是旧的 high-level API (docs):
Prior to Python 3.5, these three functions comprised the high level API to
subprocess
. You can now userun()
in many cases, but lots of existing code calls these functions.
保留旧的 API 是为了向后兼容 - 删除它们几乎没有好处,并且需要很长的弃用期才能避免破坏现有代码。
Popen
("process open") 是较低级别 API 将被 run
、check_output
等内部使用。“Popen 构造函数”记录在案 here.
子进程pipe只是子进程API对底层操作系统提供的inter-process通信特性的抽象。例如,使用 shell ls -la | grep needle
将使用管道 |
将 ls
的标准输出连接到 grep
的标准输入。要在子进程 API 中执行类似操作,您可以在生成子进程时将特殊值 subprocess.PIPE
作为标准输出句柄传递。您可能会将管道视为一个小型 FIFO 缓冲区,它将一个进程的输出引导至另一个进程的输入。