Python调用系统命令os.system()和os.popen()的实现


Posted in Python onDecember 31, 2020

作为一门脚本语言,写脚本时执行系统命令可以说很常见了,python提供了相关的模块和方法。

os模块提供了访问操作系统服务的功能,由于涉及到操作系统,它包含的内容比较多,这里只说system和popen方法。

>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

os.system()

>>> help(os.system)
Help on built-in function system in module nt:

 
system(command)
  Execute the command in a subshell.

从字面意思上看,os.system()是在当前进程中打开一个子shell(子进程)来执行系统命令。

官方说法:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

这个方法只返回状态码,执行结果会输出到stdout,也就是输出到终端。不过官方建议使用subprocess模块来生成新进程并获取结果是更好的选择。

>>> os.system('ls')
access.log douban.py mail.py myapp.py polipo proxychains __pycache__  spider.py test.py users.txt
0

os.popen()

>>> help(os.popen)
Help on function popen in module os:

popen(cmd, mode='r', buffering=-1)
  # Supply os.popen()

cmd:要执行的命令。
mode:打开文件的模式,默认为'r',用法与open()相同。
buffering:0意味着无缓冲;1意味着行缓冲;其它正值表示使用参数大小的缓冲。负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;对于其它文件,它是全缓冲。

官方说法:

Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.

The close method returns None if the subprocess exited successfully, or the subprocess's return code if there was an error.

This is implemented using subprocess.Popen;

这个方法会打开一个管道,返回结果是一个连接管道的文件对象,该文件对象的操作方法同open(),可以从该文件对象中读取返回结果。如果执行成功,不会返回状态码,如果执行失败,则会将错误信息输出到stdout,并返回一个空字符串。这里官方也表示subprocess模块已经实现了更为强大的subprocess.Popen()方法。

>>> os.popen('ls')
<os._wrap_close object at 0x7f93c5a2d780>
>>> os.popen('la')
<os._wrap_close object at 0x7f93c5a37588>
>>> /bin/sh: la: command not found

>>> f = os.popen('ls')
>>> type(f)
<class 'os._wrap_close'>

读取执行结果:

>>> f.readlines()
['access.log\n', 'douban.py\n', 'import_test.py\n', 'mail.py\n', 'myapp.py\n', 'polipo\n', 'proxychains\n', '__pycache__\n', 'spider.py\n', 'test.py\n', 'users.txt\n']

这里使用os.popen来获取设备号,使用os.system来启动macaca服务(有时间了将macaca的一些经历写写吧)。

两者的区别是:

(1)os.system(cmd)的返回值只会有0(成功),1,2

(2)os.popen(cmd)会把执行的cmd的输出作为值返回。

参考:

https://docs.python.org/3/library/os.html#os.system
https://docs.python.org/3/library/os.html#os.popen

到此这篇关于Python调用系统命令os.system()和os.popen()的实现的文章就介绍到这了,更多相关Python os.system()和os.popen()内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
分享15个最受欢迎的Python开源框架
Jul 13 Python
在Django框架中运行Python应用全攻略
Jul 17 Python
python中的内置函数max()和min()及mas()函数的高级用法
Mar 29 Python
解决安装tensorflow遇到无法卸载numpy 1.8.0rc1的问题
Jun 13 Python
使用python实现http及ftp服务进行数据传输的方法
Oct 26 Python
python ---lambda匿名函数介绍
Mar 13 Python
Python绘制全球疫情变化地图的实例代码
Apr 20 Python
python矩阵运算,转置,逆运算,共轭矩阵实例
May 11 Python
利用django创建一个简易的博客网站的示例
Sep 29 Python
Django如何重置migration的几种情景
Feb 24 Python
一些让Python代码简洁的实用技巧总结
Aug 23 Python
Python中的tkinter库简单案例详解
Jan 22 Python
Python使用Opencv实现边缘检测以及轮廓检测的实现
Dec 31 #Python
python 检测nginx服务邮件报警的脚本
Dec 31 #Python
Django 实现图片上传和下载功能
Dec 31 #Python
Python wordcloud库安装方法总结
Dec 31 #Python
Python的信号库Blinker用法详解
Dec 31 #Python
浅析python实现动态规划背包问题
Dec 31 #Python
python中doctest库实例用法
Dec 31 #Python
You might like
PHP中如何使用session实现保存用户登录信息
2015/10/20 PHP
深入理解Yii2.0乐观锁与悲观锁的原理与使用
2017/07/26 PHP
详解thinkphp中的volist标签
2018/01/15 PHP
javascript 一些用法小结
2009/09/11 Javascript
Javascript 键盘事件的组合使用实现代码
2012/05/04 Javascript
JavaScript取得鼠标绝对位置程序代码介绍
2012/09/16 Javascript
jquery ajax post提交数据乱码
2013/11/05 Javascript
jQuery拖拽 &amp; 弹出层 介绍与示例
2013/12/27 Javascript
javascript客户端遍历控件与获取父容器对象示例代码
2014/01/06 Javascript
AngularJS中的拦截器实例详解
2017/04/07 Javascript
Parcel.js + Vue 2.x 极速零配置打包体验教程
2017/12/24 Javascript
vue中设置height:100%无效的问题及解决方法
2018/07/27 Javascript
微信小程序云开发之使用云存储
2019/05/17 Javascript
JavaScript写个贪吃蛇小游戏(超详细)
2020/03/17 Javascript
js实现幻灯片轮播图
2020/08/14 Javascript
微信小程序以7天为周期连续签到7天功能效果的示例代码
2020/08/20 Javascript
[02:06]DOTA2肉山黑名单魔法终结者 敌法师中文配音鉴赏
2013/06/17 DOTA
[06:24]DOTA2亚洲邀请赛小组赛第三日 TOP10精彩集锦
2015/02/01 DOTA
python判断一个集合是否包含了另外一个集合中所有项的方法
2015/06/30 Python
浅谈Python用QQ邮箱发送邮件时授权码的问题
2018/01/29 Python
Python使用functools实现注解同步方法
2018/02/06 Python
python 用lambda函数替换for循环的方法
2018/06/09 Python
python高级特性和高阶函数及使用详解
2018/10/17 Python
使用PyQt4 设置TextEdit背景的方法
2019/06/14 Python
python爬虫 urllib模块反爬虫机制UA详解
2019/08/20 Python
python3 tkinter实现添加图片和文本
2019/11/26 Python
python 实现简单的FTP程序
2019/12/27 Python
python3实现语音转文字(语音识别)和文字转语音(语音合成)
2020/10/14 Python
纯css实现照片墙3D效果的示例代码
2017/11/13 HTML / CSS
澳大利亚自然和有机的健康美容产品一站式商店:Ziani Beauty
2017/12/28 全球购物
三年级音乐教学反思
2014/01/28 职场文书
员工培训邀请函
2014/02/02 职场文书
人力资源作业细则
2014/03/03 职场文书
就业意向书
2014/07/29 职场文书
2014幼儿园中班工作总结
2014/11/10 职场文书
2016年学校安全教育月活动总结
2016/04/06 职场文书