首页 技术 正文
技术 2022年11月16日
0 收藏 691 点赞 4,356 浏览 986 个字

(1) os.system

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

import os

os.system(‘cat /proc/cupinfo’)

(2) os.popen

该方法不但执行命令还返回执行后的信息对象,是通过一个管道文件将结果返回。

output = os.popen(‘cat /proc/cpuinfo’)

print output.read()

(3)使用模块commands模块

import commands

(status, output) = commands.getstatusoutput(‘cat /proc/cpuinfo’)

print status,output

注意1:在类unix的系统下使用此方法返回的返回值(status)与脚本或命令执行之后的返回值不等,这是因为调用了os.wait()的缘故,

具体原因就得去了解下系统wait()的实现了。需要正确的返回值(status),只需要对返回值进行右移8位操作就可以了。

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

(4) 使用模块subprocess

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

Class subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None,

stderr=None, preexec_fn=None,  close_fds=True, shell=False,

cwd=None, env=None, universal_newlines=False, startupinfo=None,

creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())

有丰富的参数可以进行配置,可供我们自定义的选项多,灵活性高。之前我使用os.system的时候遇到文件描述符被子进程继承的问题,后来通过close_fds = False 这个参数来解决的

转载:https://www.cnblogs.com/zflibra/p/4180796.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,812
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,894