作为一门脚本语言,写脚本时执行系统命令可以说很常见了,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.popen('la')

>>> /bin/sh: la: command not found

>>> f = os.popen('ls')

>>> type(f)

读取执行结果:

>>> 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的输出作为值返回。

参考:

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

python中os system_Python调用系统命令os.system()和os.popen()的实现相关推荐

  1. python中的模块调用_Python中模块互相调用的例子

    Python中模块互相调用容易出错,经常是在本地路径下工作正常,切换到其他路径来调用,就各种模块找不到了.解决方法是通过 __file__ 定位当前文件的真实路径,再通过 sys.path.appen ...

  2. 站长在线Python精讲:在Python中函数的调用详解

    欢迎你来到站长在线的站长学堂学习Python知识,本文学习的是<在Python中函数的调用详解>.本文的主要内容有:调用函数的基本语法和调用自定义函数的实例讲解. 目录 1.调用函数的基本 ...

  3. python延时执行函数_一日一技:在 Python 中实现延迟调用

    一日一技:在 Python 中实现延迟调用 收录于话题 #你不知道的 Python 71个 摄影:产品经理 产品经理的生日餐 熟悉 Golang 的同学都知道,Golang 里面有一个关键词叫做def ...

  4. python中的sys的概念和作用_Python(os和sys)理解

    Python(os和sys)理解 os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口; sys模块负责程序与python解释器的交互,提供了一系列的函数和变量,用于操控python的运行时 ...

  5. python中quit函数用法_关于 Python 中的退出命令:sys.exit(n), os._exit(n), quit(), exit()...

    sys.exit(n) 标准的退出函数,会抛出一个 SystemExit 异常,可以在捕获异常处执行其他工作,比如清理资源占用 如果 n 为 0,则表示成功; 非 0 则会产生非正常终止 另外,除了可 ...

  6. Python中使用jpype调用Jar包中的方法

    安装 pip install jpype1(注意要加后边这个1) 使用 基本流程如下: 使用jpype开启jvm 加载java类 调用java方法 关闭jvm 说明 我这里是在Python中使用Jav ...

  7. python中函数的调用_慢步python,编程中函数的概念,python中函数的声明和调用

    函数,曾经是一个很高大尚的概念.笔者是在高中数学里认识的函数,先是从y=2x+3 这条代数式开始的.y是因变量,x是自变量,y因为x取值的变化而变化. 再后来式子变成这样:f(x)=2x+3,f(x) ...

  8. python中的封装调用_Python基础之封装

    一.什么是封装 在程序设计中,封装(Encapsulation)是对具体对象的一种抽象,即将某些部分隐藏起来,在程序外部看不到,其 含义是其他程序无法调用. 要了解封装,离不开"私有化&qu ...

  9. 在python中使用autoit_Python调用autoit

    1. 安装pywin32模块,地址:http://sourceforge.net/projects/pywin32/  选择对应的版本下载 2.从autoit3\AutoItX下找到AutoItX3_ ...

最新文章

  1. 市直系统推荐市级以上表彰的_浏阳市召开第六届教育科研成果表彰大会
  2. “sockaddr_in”:“struct”类型重定义
  3. anaconda换源和恢复默认源
  4. 【LeetCode从零单排】No.8 String to Integer (丧心病狂的一道题)
  5. java分布式api网管关,分布式04-Spring Cloud Zuul Api网关 一
  6. 【Linux】cp命令
  7. 遥感方法研究张掖市1999-2010年土地利用变化
  8. Thymeleaf + Spring中的验证
  9. mysql数据库java链接,java链接MySQL数据库方法
  10. Spring源码分析之ProxyFactoryBean方式实现Aop功能的分析
  11. wm_copydata不等返回值处理 SendMessage SendMessageTimeout
  12. 网络安全实验2 信息搜集与主机发现
  13. 3.多边形曲线简化之Douglas-Peucker算法
  14. 前端开发工具WebStorm下载
  15. OCR识别技术保险保单识别系统|车险保单识别寿险保单识别|助力保险理赔
  16. JavaGUI编程 -- Swing之Icon、ImageIcon标签获取当前类同一级文件路径的资源
  17. pyecharts读取数据制作地图图表Geo
  18. aria服务器没有响应,aria2服务器错误
  19. ps ps aux 和ps -aux和 ps -ef的选择
  20. 用两种方法改错,体会封装和友员的关系!

热门文章

  1. iOS 局域网通讯 MultipeerConnectivity
  2. 知网CAJ论文 如何转换成pdf
  3. python 合并工作簿_Excel:快速合并多张表格或多个文件(工作簿)的数据(附Python代码)...
  4. 自制紧张刺激的滑雪游戏,来一把?
  5. 使用QT对接大华网络摄像头SDK的示例程序(建议收藏)
  6. 广告投放中的预算问题
  7. 微型计算机显示器的标准接口,显示器原理及接口显示器BIOS编程I(原理部分)
  8. Latex排版论文MiKTeX与Texmaker 配置使用及宏包的下载
  9. 浮沙筑塔——protues仿真C51程序之LED灯闪烁
  10. 华为鸿蒙亮利剑,华为亮利剑,超级主镜头+鸿蒙OS,所有期许或将如愿以偿