Python模块 os commands

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

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

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

import osprint 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‘

#LinuxPython 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import os>>> os.name‘posix‘>>> #WindowsPython 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32Type "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 lo2: 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 eth03: 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:ff0

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

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

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

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

import osprint 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\mainC:\Users\YangQing\PycharmProjects\Test\modules

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

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

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

import osprint 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\mainC:\Users\YangQing\PycharmProjects\Test\modules\main\test.logC:\Users\YangQing\PycharmProjects\Test

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

(5)

(6)

时间: 2024-08-30 07:05:15

Python模块 os commands的相关文章

python模块—OS

OS模块也是我们平时工作中很常用到的一个模块,通过os模块调用系统命令,获得路劲,获取操作系统的类型等都是使用该模块. 1.获取系统类型 例子: >>> import os >>> print(os.name) posix 2.执行系统命令 例子1: >>> import os >>> os.system("ifconfig") ens33: flags=4163<UP,BROADCAST,RUNNING,M

python模块 os&amp;sys&amp;subprocess&amp;hashlib模块

os模块 # os模块可根据带不带path分为两类 # 不带path print(os.getcwd()) # 得到当前工作目录 print(os.name) # 指定你正在使用的操作系统,windows为nt,linux为“posix" os.shell() # 运行shell命令 print(os.environ) # 返回操作系统所有的环境变量 print(os.getenv("home")) # 读取指定环境变量的值 os.environ.setdefault(&qu

python模块-os模块和sys模块

os模块 os.getcwd()  获取当前的工作目录 os.chdir('绝对路径/相对于当前工作目录的路径')  改变工作目录,相当于shell的cd命令,例如Windows平台下os.chdir('D:\PythonScripts\\test\c'),项目那一层的目录必须用双斜线分割,其他层级的双斜线和单斜线都可,在linux和unix平台下用/分割 os.curdir  返回当前路径. os.pardir  返回当前路径的上一层路径,即.. os.mkdir('dir')  生成单级目录

python模块os

一.os模块概述 Python os模块包含普遍的操作系统功能.如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的.(一语中的) 二.常用方法 1.os.name 输出字符串指示正在使用的平台.如果是window 则用'nt'表示,对于Linux/Unix用户,它是'posix'. 2.os.getcwd() 函数得到当前工作目录,即当前Python脚本工作的目录路径. #!/bin/env python #-*- encoding=utf8 -*- import os if __nam

Python模块 - os.path() 模块

1. 使用模块需要先用 import 导入模块 import os 2.常见的OS模块用法 详细的os模块使用方式不做解释,网上有非常详细的资料或者博文 Python OS 文件/目录方法 Python os.path() 模块 点击上面链接可以直接跳转到 菜鸟教程 网站查看相关资料 3.个人练习 3.1>文件重命名和删除 import os # 文件的重命名 # r为转移字符,此处为我PC文件的绝对路径 os.rename(r'E:\Python上路\名片管理系统\xr_logo.png',

python模块: OS模块

#!/bin/env python#!-*- coding:UTF-8 -*- import osprint os.name         #输出主机平台print os.getcwd()     #输出当前目录print os.listdir(os.getcwd())       #输出当前目录的文件(横向) for i in os.listdir(os.getcwd()):   #输出当前目录的文件(纵向)    print i os.makedirs("/tmp/tong/123&quo

python—模块-os

os实现的是与系统的交互,比如创建一个文件夹,删除一个文件,查看一个文件的大小 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd() #把这个写到脚本中,就会打印出这个脚本是从哪里执行的,就是python解释器是从哪里启动的 >>> import os >>> print(os.getcwd()) C:\Users\PC 原文地址:https://www.cnblogs.com/xiaobai-yemao/p/8870743.html

python模块--os&amp;sys&amp;shutil

shutil 高级的 文件.文件夹.压缩包 处理模块 shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中,可以部分内容   shutil.copyfile(src, dst)拷贝文件   shutil.copymode(src, dst)仅拷贝权限.内容.组.用户均不变   shutil.copystat(src, dst)拷贝状态的信息,包括:mode bits, atime, mtime, flags   shutil.copy(sr

python中的commands模块,执行出错:&#39;{&#39; 不是内部或外部命令,也不是可运行的程序 或批处理文件。

最近发现了python的commands模块,查看了下源码,使用的popen封装的,形成三个函数getstatus(), getoutput(), getstatusoutput() 源码如下: def getstatus(file): """Return output of "ls -ld <file>" in a string.""" import warnings warnings.warn("co