程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(5)

Python—执行系统命令的四种方法(os.system、os.popen、commands、subprocess)

发布于2020-02-10 15:28     阅读(652)     评论(0)     点赞(29)     收藏(1)


一、os.system方法

这个方法是直接调用标准C的system() 函数,仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息。

os.system(cmd)的返回值。如果执行成功,那么会返回0,表示命令执行成功。否则,则是执行错误。

使用os.system返回值是脚本的退出状态码,该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码。

os.system()返回值为0        linux命令返回值也为0。

os.system()返回值为256,十六位二进制数示为:00000001,00000000,高八位转成十进制为 1        对应   linux命令返回值 1。

os.system()返回值为512,十六位二进制数示为:00000010,00000000,高八位转成十进制为 2        对应   linux命令返回值 2。

1
2
3
import os
result = os.system('cat /etc/passwd')
print(result)      # 0

二、os.popen方法

os.popen()方法不仅执行命令而且返回执行后的信息对象(常用于需要获取执行命令后的返回信息),是通过一个管道文件将结果返回。通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。

1
2
3
import os
result = os.popen('cat /etc/passwd')
print(result.read())

三、commands模块

1
2
3
4
5
6
7
8
import commands
 
status = commands.getstatus('cat /etc/passwd')
print(status)
output = commands.getoutput('cat /etc/passwd')
print(output)
(status, output) = commands.getstatusoutput('cat /etc/passwd')
print(status, output)

四、subprocess模块

Subprocess是一个功能强大的子进程管理模块,是替换os.system ,os.spawn* 等方法的一个模块。

当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess。

1
2
3
4
5
6
import subprocess
res = subprocess.Popen('cat /etc/passwd', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # 使用管道
# print res.stdout.read()  # 标准输出
for line in res.stdout.readlines():
    print line
res.stdout.close()         # 关闭

五、总结:

os.system:获取程序执行命令的返回值。

os.popen: 获取程序执行命令的输出结果。

commands:获取返回值和命令的输出结果。

https://www.jb51.net/article/142787.htm



所属网站分类: 技术文章 > 博客

作者:小兔子乖乖

链接:https://www.pythonheidong.com/blog/article/230686/a2afcce0ba9dce2c4dec/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

29 0
收藏该文
已收藏

评论内容:(最多支持255个字符)