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多线程(python多线程简明教程)
Jun 09 Python
详解Python中用于计算指数的exp()方法
May 14 Python
python分治法求二维数组局部峰值方法
Apr 03 Python
解决python3 json数据包含中文的读写问题
May 10 Python
对numpy中的transpose和swapaxes函数详解
Aug 02 Python
pycharm使用matplotlib.pyplot不显示图形的解决方法
Oct 28 Python
Python基础教程之if判断,while循环,循环嵌套
Apr 25 Python
python2.7的flask框架之引用js&amp;css等静态文件的实现方法
Aug 22 Python
使用Python爬虫库requests发送请求、传递URL参数、定制headers
Jan 25 Python
Python3+selenium实现cookie免密登录的示例代码
Mar 18 Python
python自动从arxiv下载paper的示例代码
Dec 05 Python
浅析Python实现DFA算法
Jun 26 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 curl库实现整站克隆功能
2015/02/12 PHP
div移动 输入框不能输入的问题
2009/11/19 Javascript
jQuery 开天辟地入门篇一
2009/12/09 Javascript
关于火狐(firefox)及ie下event获取的两种方法
2012/12/27 Javascript
Node.js编程中客户端Session的使用详解
2015/06/23 Javascript
javascript中for/in循环及使用技巧
2015/09/01 Javascript
jQuery实现美观的多级动画效果菜单代码
2015/09/06 Javascript
jQuery解析json数据实例分析
2015/11/24 Javascript
JS工作中的小贴士之”闭包“与事件委托的”阻止冒泡“
2016/06/16 Javascript
JS实现的图片预览插件与用法示例【不上传图片】
2016/11/25 Javascript
详谈Angular路由与Nodejs路由的区别
2017/03/05 NodeJs
jQuery插件FusionCharts绘制ScrollColumn2D图效果示例【附demo源码下载】
2017/03/22 jQuery
Vue实现动态创建和删除数据的方法
2018/03/17 Javascript
vue实现通讯录功能
2018/07/14 Javascript
js jquery 获取某一元素到浏览器顶端的距离实现方法
2018/09/05 jQuery
微信小程序自定义tabBar组件开发详解
2020/09/24 Javascript
webpack+express实现文件精确缓存的示例代码
2020/06/11 Javascript
Python实现全局变量的两个解决方法
2014/07/03 Python
Python利用字典将两个通讯录文本合并为一个文本实例
2018/01/16 Python
python 拷贝特定后缀名文件,并保留原始目录结构的实例
2018/04/27 Python
对python dataframe逻辑取值的方法详解
2019/01/30 Python
利用Python绘制有趣的万圣节南瓜怪效果
2019/10/31 Python
TFRecord文件查看包含的所有Features代码
2020/02/17 Python
Python递归求出列表(包括列表中的子列表)的最大值实例
2020/02/27 Python
Python figure参数及subplot子图绘制代码
2020/04/18 Python
CSS3制作炫酷带方向感应的鼠标滑过图片3D动画
2016/03/16 HTML / CSS
世界各地的当地人的食物体验:Eatwith
2019/07/26 全球购物
团代会闭幕词
2015/01/28 职场文书
海底两万里读书笔记
2015/06/26 职场文书
2015入党自传书范文
2015/06/26 职场文书
中学校园广播稿
2015/08/18 职场文书
七夕情人节问候语
2015/11/11 职场文书
SpringBoot整合Mybatis Generator自动生成代码
2021/08/23 Java/Android
mysql中数据库覆盖导入的几种方式总结
2022/03/25 MySQL
Java虚拟机内存结构及编码实战分享
2022/04/07 Java/Android
MySQL索引 高效获取数据的数据结构
2022/05/02 MySQL