Python模块 os commands

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python模块 os commands相关的知识,希望对你有一定的参考价值。

  在自动化运维和测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告(从而发送测试报告邮件),经常要对大量文件和大量路径进行操作,对于python而言这就需要依赖于os模块。下面就学习下os模块常用的几个方法。

>>> import os     #导入os模块
>>> help(os)      #查看os模块帮助文档,里面详细的模块相关函数和使用方法

>>> dir(os)        #查看os模块所支持的方法

import os
print dir(os)

[‘F_OK‘, ‘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‘, ‘R_OK‘, ‘SEEK_CUR‘, ‘SEEK_END‘, ‘SEEK_SET‘, ‘TMP_MAX‘, ‘UserDict‘, ‘W_OK‘, ‘X_OK‘, ‘_Environ‘, ‘__all__‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘_copy_reg‘, ‘_execvpe‘, ‘_exists‘, ‘_exit‘, ‘_get_exports_list‘, ‘_make_stat_result‘, ‘_make_statvfs_result‘, ‘_pickle_stat_result‘, ‘_pickle_statvfs_result‘, ‘abort‘, ‘access‘, ‘altsep‘, ‘chdir‘, ‘chmod‘, ‘close‘, ‘closerange‘, ‘curdir‘, ‘defpath‘, ‘devnull‘, ‘dup‘, ‘dup2‘, ‘environ‘, ‘errno‘, ‘error‘, ‘execl‘, ‘execle‘, ‘execlp‘, ‘execlpe‘, ‘execv‘, ‘execve‘, ‘execvp‘, ‘execvpe‘, ‘extsep‘, ‘fdopen‘, ‘fstat‘, ‘fsync‘, ‘getcwd‘, ‘getcwdu‘, ‘getenv‘, ‘getpid‘, ‘isatty‘, ‘kill‘, ‘linesep‘, ‘listdir‘, ‘lseek‘, ‘lstat‘, ‘makedirs‘, ‘mkdir‘, ‘name‘, ‘open‘, ‘pardir‘, ‘path‘, ‘pathsep‘, ‘pipe‘, ‘popen‘, ‘popen2‘, ‘popen3‘, ‘popen4‘, ‘putenv‘, ‘read‘, ‘remove‘, ‘removedirs‘, ‘rename‘, ‘renames‘, ‘rmdir‘, ‘sep‘, ‘spawnl‘, ‘spawnle‘, ‘spawnv‘, ‘spawnve‘, ‘startfile‘, ‘stat‘, ‘stat_float_times‘, ‘stat_result‘, ‘statvfs_result‘, ‘strerror‘, ‘sys‘, ‘system‘, ‘tempnam‘, ‘times‘, ‘tmpfile‘, ‘tmpnam‘, ‘umask‘, ‘unlink‘, ‘unsetenv‘, ‘urandom‘, ‘utime‘, ‘waitpid‘, ‘walk‘, ‘write‘]

(1)os.name获取当前正在使用的平台,Windows 返回 ‘nt‘; Linux 返回’posix‘

#Linux
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.name
‘posix‘
>>>
#Windows
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.name
‘nt‘
>>>

(2)os.system(command)执行shell命令

#Windows
>>> os.system(‘netstat -an |findstr 8080‘)
 TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING
 TCP    192.168.31.37:6959     183.192.196.205:8080   CLOSE_WAIT
 TCP    [::]:8080              [::]:0                 LISTENING
#Linux
>>> os.system(‘ip addr list‘)
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
   inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
   link/ether 66:95:73:bf:5f:97 brd ff:ff:ff:ff:ff:ff
   inet 218.207.221.92/27 brd 218.207.221.95 scope global eth0
3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000
   link/ether b2:91:14:7e:78:ae brd ff:ff:ff:ff:ff:ff
0

(3)当前路径及路径下的文件

  os.getcwd():查看当前所在路径。

  os.listdir(path):列举目录下的所有文件。返回的是列表类型。

  os.path.abspath(path):返回path的绝对路径。

import os
print os.getcwd()
print os.listdir(os.getcwd())
print os.path.abspath(‘.‘)
print os.path.abspath(‘..‘)

运行结果:
C:\Users\YangQing\PycharmProjects\Test\modules\main
[‘client.py‘, ‘M_os.py‘, ‘rizhi.py‘, ‘shijian.py‘, ‘test.log‘, ‘__init__.py‘, ‘__init__.pyc‘]
C:\Users\YangQing\PycharmProjects\Test\modules\main
C:\Users\YangQing\PycharmProjects\Test\modules

(4)查看路径的文件夹部分和文件名部分

  os.path.split(path):将路径分解为(文件夹,文件名),返回的是元组类型。

  os.path.join(path1,path2,...):将path进行组合,若其中有绝对路径,则之前的path将被删除。

import os
print os.path.split(‘.‘)
print os.path.split(‘C:\Users\YangQing\PycharmProjects\Test\modules\main\test.log‘)
print os.path.split(‘C:\Users\YangQing\PycharmProjects\Test\modules\main\\‘)
print os.path.split(‘C:\Users\YangQing\PycharmProjects\Test\modules\main‘)
print os.path.join(‘C:\Users\YangQing\PycharmProjects\Test\modules‘,‘main‘)
print os.path.join(‘C:\Users\YangQing\PycharmProjects\Test\modules\main‘,‘test.log‘)
print os.path.join(‘C:\Users\YangQing\PycharmProjects\Test\modules\main‘,‘C:\Users\YangQing\PycharmProjects\Test‘)

运行结果:
(‘‘, ‘.‘)
(‘C:\\Users\\YangQing\\PycharmProjects\\Test\\modules‘, ‘main\test.log‘)
(‘C:\\Users\\YangQing\\PycharmProjects\\Test\\modules\\main‘, ‘‘)
(‘C:\\Users\\YangQing\\PycharmProjects\\Test\\modules‘, ‘main‘)
C:\Users\YangQing\PycharmProjects\Test\modules\main
C:\Users\YangQing\PycharmProjects\Test\modules\main\test.log
C:\Users\YangQing\PycharmProjects\Test

  从上述例子中可以看出,若路径字符串最后一个字符是\,则只有文件夹部分有值;若路径字符串中均无\,则只有文件名部分有值。若路径字符串有\,且不在最后,则文件夹和文件名均有值。且返回的文件夹的结果不包含\.

(5)


(6)


本文出自 “DreamScape” 博客,请务必保留此出处http://dyqd2011.blog.51cto.com/3201444/1980528

以上是关于Python模块 os commands的主要内容,如果未能解决你的问题,请参考以下文章

Python的logging模块os模块commands模块与sys模块

学习笔记(11月10日)--python常用内置模块的使用(logging, os, command)

Python模块 logging os commands

Python 使用OS模块调用 cmd

python实现系统脚本命令调用模块---subprocess模块

Python模块 - subprocess