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 相关文章推荐
python线程、进程和协程详解
Jul 19 Python
在django中使用自定义标签实现分页功能
Jul 04 Python
详解Python开发中如何使用Hook技巧
Nov 01 Python
PyQt5 QSerialPort子线程操作的实现
Apr 21 Python
python爬虫URL重试机制的实现方法(python2.7以及python3.5)
Dec 18 Python
基于python生成器封装的协程类
Mar 20 Python
详解Python Matplotlib解决绘图X轴值不按数组排序问题
Aug 05 Python
详细整理python 字符串(str)与列表(list)以及数组(array)之间的转换方法
Aug 30 Python
Python 解决火狐浏览器不弹出下载框直接下载的问题
Mar 09 Python
python3用PyPDF2解析pdf文件,用正则匹配数据方式
May 12 Python
Django+Django-Celery+Celery的整合实战
Jan 20 Python
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
Jun 09 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
mysql limit查询优化分析
2008/11/12 PHP
PHP session有效期session.gc_maxlifetime
2011/04/20 PHP
PHP之APC缓存详细介绍 apc模块安装
2014/01/13 PHP
Zend Framework教程之Zend_Config_Ini用法分析
2016/03/23 PHP
CakePHP框架Session设置方法分析
2017/02/23 PHP
比较详细的关于javascript 解析json的代码
2009/12/16 Javascript
JavaScript中继承的一些示例方法与属性参考
2010/08/07 Javascript
来自国外的30个基于jquery的Web下拉菜单
2012/06/22 Javascript
有关于JS辅助函数inherit()的问题
2013/04/07 Javascript
js Select下拉列表框进行多选、移除、交换内容的具体实现方法
2013/08/13 Javascript
js 高效去除数组重复元素示例代码
2013/12/19 Javascript
jquery实现pager控件示例
2014/04/09 Javascript
Jquery给基本控件的取值、赋值示例
2014/05/23 Javascript
node.js中的fs.read方法使用说明
2014/12/17 Javascript
nodejs中实现sleep功能实例
2015/03/24 NodeJs
jquery简单实现带渐显效果的选项卡菜单代码
2015/09/01 Javascript
JS实现的鼠标跟随代码(卡通手型点击效果)
2015/10/26 Javascript
Knockoutjs 学习系列(一)ko初体验
2016/06/07 Javascript
jquery easyui dataGrid动态改变排序字段名的方法
2017/03/02 Javascript
浅谈关于axios和session的一些事
2017/07/13 Javascript
Vue中使用vux配置代码详解
2018/09/16 Javascript
layui原生表单验证的实例
2019/09/09 Javascript
[04:44]DOTA2 2017全国高校联赛视频回顾
2017/08/21 DOTA
python 根据正则表达式提取指定的内容实例详解
2016/12/04 Python
利用Python破解验证码实例详解
2016/12/08 Python
简单学习Python多进程Multiprocessing
2017/08/29 Python
使用python实现抓取腾讯视频所有电影的爬虫
2019/04/15 Python
Python实现中值滤波去噪方式
2019/12/18 Python
Python类的绑定方法和非绑定方法实例解析
2020/03/04 Python
Python 创建TCP服务器的方法
2020/07/28 Python
html5实现图片转圈的动画效果——让页面动起来
2017/10/16 HTML / CSS
安全的后院和健身蹦床:JumpSport
2019/07/15 全球购物
瑞士网球商店:Tennis-Point
2020/03/12 全球购物
业务员薪酬管理制度
2014/01/15 职场文书
天那边观后感
2015/06/09 职场文书
血轮眼轮回眼特效 html+css
2021/03/31 HTML / CSS