CODE/2022-10-14

python 中执行 shell 命令

这里介绍一下 python 执行 shell 命令的四种方法:
1、os 模块中的 os.system()这个函数来执行 shell 命令
plain text_snippet
Plain Text · 3 lines|
>>> os.system('ls')
anaconda-ks.cfg install.log install.log.syslog send_sms_service.py sms.py
0
注,这个方法得不到 shell 命令的输出。
2、popen()#这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。
plain text_snippet
Plain Text · 5 lines|
>>> import os
>>> str = os.popen("ls").read()
>>> a = str.split("\n")
>>> for b in a:
print b
这样得到的结果与第一个方法是一样的。
3、commands 模块#可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位
commands.getstatusoutput(cmd)返回(status,output)
commands.getoutput(cmd)只返回输出结果
commands.getstatus(file)返回 ls -ld file 的执行结果字符串,调用了 getoutput,不建议使用这个方法。
4、subprocess 模块
使用 subprocess 模块可以创建新的进程,可以与新建进程的输入 / 输出 / 错误管道连通,并可以获得新建进程执行的返回状态。使用 subprocess 模块的目的是替代 os.system()、os.popen*()、commands.* 等旧的函数或模块。
import subprocess
1、subprocess.call(command, shell=True)
#会直接打印出结果。
2、subprocess.Popen(command, shell=True) 也可以是 subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就可以输出结果了。
如果 command 不是一个可执行文件,shell=True 是不可省略的。
shell=True 意思是 shell 下执行 command
这四种方法都可以执行 shell 命令。
COMPANION ESSAYS / 思想脉络与互照篇目
同卷深读2026-05-22 ·

python3安装在centos详细教程

同属「系统工程卷」脉络衍生思考与工程推演推演阅读 →
跨界互照2026-08-22 ·

我的书架:03|金融经管:经济运行、金融体系与企业治理

我的书架:03|金融经管:经济运行、金融体系与企业治理

跨领域对照思辨 · 从「思想随笔」视界互为印证推演阅读 →
RELATED INDEX / 相关阅读索引
柯航hang.ke·© 2014—2026
CC BY-NC 4.0·