为什么当我触发终端命令时 python 返回 0?

The*_*ech 0 python terminal

我正在尝试让 python 与我的终端交互,我尝试了以下脚本,当我希望它显示当前目录的内容时,它返回 0:

>>> import os
>>> os.system("ls")
0
Run Code Online (Sandbox Code Playgroud)

它为什么这样做?(注意这是一个 mac 命令,因为我在 mac 上)

Cha*_*ffy 5

0ls成功完成时的退出状态。

如果要捕获文件名列表,则需要其标准输出,而不是退出状态。os.system()不返回那个。

我建议:

import subprocess
output = subprocess.check_output(["ls"]) # will raise an exception if ls fails
Run Code Online (Sandbox Code Playgroud)