Python 执行 Shell 命令并获取输出的几种方法

温以宁
温以宁
发布时间:2026-10-13 | 4人浏览过
原创

本文介绍在 Python 中执行 Shell 命令并获取输出结果的三种方式。首先分析内置模块 os.system 的局限性,仅能返回退出状态码;接着演示使用 subprocess 模块通过 Popen 和管道捕获标准输出的方法;最后探讨第三方库 sh 的高级用法,包括命令映射、参数处理及超时控制,并提供解决复杂命令调用的替代方案。

首先,可以使用 Python 的内置模块 来执行系统命令。

>>> import os
>>> code = os.system("pwd && sleep 2")
# /User/zhipeng
>>> print code
# 0

然而, 模块中的 system 函数存在一个明显问题:它只能获取命令执行的结束状态码,而无法直接捕获命令的标准输出内容。

为了获取命令的输出结果,建议使用内置模块 。

>>> import subprocess
>>> subprocess.Popen("pwd && sleep 2", shell=True, cwd="/home")
# <subprocess.Popen object at 0x106498310>
# /home

>>> sub = subprocess.Popen("pwd && sleep 2", shell=True, stdout=subprcess.PIPE)
>>> sub.wait()
>>> print sub.stdout.read()
# /User/zhipeng
subprocess.Popen还支持一些别的参数 
bufsize,executable=None, stdin=None, stdout=None, stderr=None 
preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None 
universal_newlines=False, startupinfo=None, creationflags=0

此外,还可以使用第三方模块 来简化 Shell 命令的调用。

# pip install sh
>>> from sh import ifconfig
>>> print ifconfig("eth0")

>>> from sh import bash
>>> bash("pwd")
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/Library/Python/2.7/site-packages/sh.py", line 1021, in __call__
 return RunningCommand(cmd, call_args, stdin, stdout, stderr)
 File "/Library/Python/2.7/site-packages/sh.py", line 486, in __init__
 self.wait()
 File "/Library/Python/2.7/site-packages/sh.py", line 500, in wait
 self.handle_command_exit_code(exit_code)
 File "/Library/Python/2.7/site-packages/sh.py", line 516, in handle_command_exit_code
 raise exc(self.ran, self.process.stdout, self.process.stderr)
sh.ErrorReturnCode_126: 
 RAN: '/bin/bash ls'
 STDOUT:
 STDERR:
/bin/ls: /bin/ls: cannot execute binary file

# 不能这么用
>>> from sh import ls
>>> ls()
# hello.txt 1.txt
# ls -al
>>> ls(a=True, l=True)
# ls(al=True) 是不可以的

虽然 功能强大,但其操作相对复杂,在项目中直接使用可能会带来不便,且难以直接处理多个命令的同时执行。不过,可以通过其他替代方式来解决这些问题。

# bash -c command 可以很好的解决这个问题
# bash -c "sleep 1 && pwd"
>>> result = bash(c="pwd", _timeout=1, _cwd="/home")
>>> print result
# -rw-r--r--@ 1 zhipeng staff 0 10 13 18:30 hello.txt
# -rw-r--r--@ 1 zhipeng staff 0 10 13 18:30 1.txt

>>> result = bash(c="pwd", _timeout=1, _cwd="/")
>>> print result
# /
>>> bash(c="pwd && sleep 2", _timeout=1)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/Library/Python/2.7/site-packages/sh.py", line 1021, in __call__
 return RunningCommand(cmd, call_args, stdin, stdout, stderr)
 File "/Library/Python/2.7/site-packages/sh.py", line 486, in __init__
 self.wait()
 File "/Library/Python/2.7/site-packages/sh.py", line 498, in wait
 raise TimeoutException(-exit_code)
sh.TimeoutException
参数里面可以添加非命令参数. 需要以_开头, 例如上面的_timeout, _cwd. 详见sh.py 源码 

还支持以下参数 

internal_bufsize, err_bufsize, tee, done, in, decode_errors, tty_in, 
out, cwd, timeout_signal, bg, timeout, with, ok_code, err, env, no_out,

参考资源如下:

https://github.com/amoffat/sh/blob/master/sh.py https://github.com/amoffat/sh

以上关于 Python 运行 Shell 命令并获取输出结果的实例介绍完毕,希望能为读者提供有价值的参考,也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表