python中执行shell命令的4种方法

这里介绍一下python执行shell命令的四种方法:

1、os模块中的os.system()这个函数来执行shell命令

>>> os.system('ls')
anaconda-ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,这个方法得不到shell命令的输出。

2、popen()

这个方法能得到命令执行后的结果是一个字符串,要自行处理才能得到想要的信息。

>>> import os
>>> str = os.popen("ls").read()
>>> a = str.split("\n")
>>> for b in a:
        print b

这样得到的结果与第一个方法是一样的。

3、commands模块

可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位

import commands
a,b = commands.getstatusoutput('ls')
a是退出状态
b是输出的结果。
>>> import commands
>>> a,b = commands.getstatusoutput('ls')
>>> print a
0
>>> print b
anaconda-ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回输出结果

commands.getstatus(file)返回ls -ld file 的执行结果字符串,调用了getoutput,不建议使用这个方法。

扫描二维码关注公众号,回复: 10437802 查看本文章

4、subprocess模块

使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen()、commands.等旧的函数或模块。

import subprocess

  • subprocess.call(command, shell=True) 会直接打印出结果。

  • subprocess.Popen(command, shell=True) 也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 这样就可以输出结果了。

如果command不是一个可执行文件,shell=True是不可省略的。

shell=True意思是shell下执行command

这四种方法都可以执行shell命令。

原文链接: https://blog.51cto.com/zhou123/1312791 文源网络,仅供学习之用,如有侵权,联系删除。

我将优质的技术文章和经验总结都汇集在了我的公众号【Python圈子】里。

在学习Python的道路上肯定会遇见困难,别慌,我这里有一套学习资料,包含40+本电子书,600+个教学视频,涉及Python基础、爬虫、框架、数据分析、机器学习等,不怕你学不会!还有学习交流群,一起学习进步~ file

发布了52 篇原创文章 · 获赞 1 · 访问量 3540

猜你喜欢

转载自blog.csdn.net/wulishinian/article/details/105218468