Python教程:OS与sys模块用法教程
一、Python os模块
包含普遍的操作系统功能,如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。
1、os.access()
查看文件是否有指定权限,有则返回True否则返回flase
os.access(path, mode)
- path:指定文件路径
- mode:参数有F_OK(是否存在),R_OK(可读),W_OK(可写),X_OK(可执行)
>>> os.access("/python/test.py",os.F_OK) #是否存在
True
>>> os.access("/python/test.py",os.R_OK) #是否可读
True
>>> os.access("/python/test.py",os.W_OK) #是否可写
True
>>> os.access("/python/test.py",os.X_OK) #是否可执行
False
2、os.chdir()
方法用于改变当前工作目录到指定的路径。
>>> os.getcwd() #查看当前工作路径
"/python
>>> os.chdir("/root/") #修改当前工作路径到‘/root’
>>> os.getcwd()
"/root"
3、os.chmod()
方法用于更改文件或目录的权限。
权限指定:
- stat.S_IXOTH: 其他用户有执行权0o001
- stat.S_IWOTH: 其他用户有写权限0o002
- stat.S_IROTH: 其他用户有读权限0o004
- stat.S_IRWXO: 其他用户有全部权限(权限掩码)0o007
- stat.S_IXGRP: 组用户有执行权限0o010
- stat.S_IWGRP: 组用户有写权限0o020
- stat.S_IRGRP: 组用户有读权限0o040
- stat.S_IRWXG: 组用户有全部权限(权限掩码)0o070
- stat.S_IXUSR: 拥有者具有执行权限0o100
- stat.S_IWUSR: 拥有者具有写权限0o200
- stat.S_IRUSR: 拥有者具有读权限0o400
- stat.S_IRWXU: 拥有者有全部权限(权限掩码)0o700
- stat.S_ISVTX: 目录里文件目录只有拥有者才可删除更改0o1000
- stat.S_ISGID: 执行此文件其进程有效组为文件所在组0o2000
- stat.S_ISUID: 执行此文件其进程有效用户为文件所有者0o4000
- stat.S_IREAD: windows下设为只读
- stat.S_IWRITE: windows下取消只读
# ll
---------- 1 nobody nobody 167 9月 10 13:43 test.py
>>> import stat,os
>>> os.chmod("/python/test.py",stat.S_IXOTH) #其他用户有可执行权限
[root@python python]# ll test.py
---------x 1 nobody nobody 167 9月 10 13:43 test.py
>>> os.chmod("/python/test.py",stat.S_IWOTH) #写权限
>>> os.chmod("/python/test.py",stat.S_IROTH) #读权限
>>> os.chmod("/python/test.py",stat.S_IRWOT) #全部权限
>>> os.chmod("/python/test.py",stat.S_IXGRP) #组用户有执行权限
[root@python python]# ll test.py
------x--- 1 nobody nobody 167 9月 10 13:43 test.py
#注意修改权限会消除以前的权限,只保留修改的权限
>>> os.chmod("/python/test.py",stat.S_IWGRP) #组用户有写权限
>>> os.chmod("/python/test.py",stat.S_IRGRP) #组用户有读权限
>>> os.chmod("/python/test.py",stat.S_IRWXG) #组用户有所有权限
>>> os.chmod("/python/test.py",stat.S_IXUSR) #拥有者有执行权限
>>> os.chmod("/python/test.py",stat.S_IWUSR) #拥有者有写权限
>>> os.chmod("/python/test.py",stat.S_IRUSR) #拥有者有读权限
>>> os.chmod("/python/test.py",stat.S_IRWXU) #拥有者有所有权限
[root@python python]# ll test.py
-rwx------ 1 nobody nobody 167 9月 10 13:43 test.py
4、os.chown()
方法用于更改文件所有者,如果不修改可以设置为 -1, 你需要超级用户权限来执行权限修改操作。
只支持在 Unix 下使用。
>>> os.chown("/python/test.py",0,0) #设置文件的UID为0,root用户,GID为0,root组
[root@python python]# ll test.py
-rwx------ 1 root root 167 9月 10 13:43 test.py
5、os.chroot()
方法用于更改当前进程的根目录为指定的目录,使用该函数需要管理员权限。
6、os.close()
方法用于关闭指定的文件描述符 fd。
>>> os.name #判断现在的实用平台,windows返回‘nt’,linux返回
"posix"
>>> os.getcwd() #返回当前工作的目录
"/root"
>>> os.listdir(".") #返回指定目录下所有的文件和目录名
["file.txt", "test", "caidan.py", "test.txt", "test.py", "test1.py", "enumerate.py", "login.py"]
>>> os.remove("test1.py") #删除指定文件
>>> os.listdir(".")
["file.txt", "test", "caidan.py", "test.txt", "test.py", "enumerate.py", "login.py"]
>>> os.rmdir("aaa") #删除指定目录
>>> os.mkdir("directory") #创建目录,只能创建一层目录
>>>os.path.isfile()——判断指定对象是否为文件。是返回True,否则False
>>> os.path.isfile("test.py") #为文件返回True
True
>>> os.path.isfile("directory") #此为目录则返回false
False
>>> os.path.isdir("directory") #判断指定对象是否为目录。
True
>>> os.path.exists("/python/test.py") #判断指定的对象是否存在
True
>>> os.path.exists("/python/caidan")
False
>>> os.path.split("/python/test.py") #返回路径的目录和文件名
("/python", "test.py")
>>> os.getcwd() #获取当前工作的目录
"/python"
>>> os.system("pwd") #执行shell命令
/python
0
>>> os.system("echo "hello world!"")
hello world!
0
>>> os.path.getsize("directory") #获得文件的大小,如果为目录返回0
4096
>>> os.path.abspath(".") #获得绝对路径
"/python"
>>> os.path.join("/python/directory/","test.py") #链接目录和文件名
"/python/directory/test.py"
>>> os.path.basename("/python/directory/test.py") #返回文件名
"test.py"
>>> os.path.basename("/python/directory")
"directory"
>>> os.path.dirname("/root/directory/test.py") #返回文件路径
"/root/directory"
>>> os.path.getmtime(".") #返回在此path下最后一次修改的时间戳
1510553280.2887046
二、sys模块
提供了一系列有关Python运行环境的变量和函数
sys.argv命令行参数List,第一个元素是程序本身路径
import sys
#sys.argv[0] 获取脚本名
#sys.argv[1] 获取第一个参数
print("脚本名称:{}".format(sys.argv[0]))
for i in sys.argv:
if i == sys.argv[0]:
continue
print("参数为:",i)
print("总参数个数:{}".format(len(sys.argv)-1)
[root@python python]# ./sysargv.py s1 s2 s3 s4 s5
脚本名称:./sysargv.py
参数为: s1
参数为: s2
参数为: s3
参数为: s4
参数为: s5
总参数个数:5
sys.modules.keys() 返回所有已经导入的模块列表
"""
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:711312441
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
"""
>>> import sys
>>> sys.modules.keys()
dict_keys(["_sysconfigdata", "posixpath", "rlcompleter", "stat", "encodings.latin_1", "atexit", "io", "zipimport", "_codecs", "_frozen_importlib_external", "sys", "_weakrefset", "_sitebuiltins", "_warnings", "marshal", "os", "genericpath", "encodings", "abc", "codecs", "_imp", "_frozen_importlib", "os.path", "_weakref", "_collections_abc", "readline", "encodings.aliases", "errno", "_io", "site", "_signal", "builtins", "sysconfig", "encodings.utf_8", "__main__", "_stat", "posix", "_thread"])
sys.exc_info() 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
>>> sys.exc_info()
(None, None, None)
sys.exit(n) 退出程序,正常退出时exit(0)
>>> sys.exit()
sys.hexversion 获取Python解释程序的版本值,16进制格式如:0x020403F0
>>> import sys
>>> sys.hexversion
50660592
sys.version 获取Python解释程序的版本信息
>>> sys.version
"3.5.4 (default, Sep 22 2017, 10:57:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)]"
sys.maxsize 最大的Int值
>>> sys.maxsize
9223372036854775807
sys.maxunicode 最大的Unicode值
>>> sys.maxunicode
1114111
sys.modules 返回系统导入的模块字段,key是模块名,value是模块
>>> sys.modules
{"encodings.latin_1": <module "encodings.latin_1" from "/usr/local/python35/lib/python3.5/encodings/latin_1.py">, "io": <module "io" from "/usr/local/python35/lib/python3.5/io.py">, "builtins": <module "builtins" (built-in)>, "_sitebuiltins": <module "_sitebuiltins" from "/usr/local/python35/lib/python3.5/_sitebuiltins.py">, "zipimport": <module "zipimport" (built-in)>, "encodings": <module "encodings" from "/usr/local/python35/lib/python3.5/encodings/__init__.py">, "re": <module "re" from "/usr/local/python35/lib/python3.5/re.py">, "stat": <module "stat" from "/usr/local/python35/lib/python3.5/stat.py">, "_imp": <module "_imp" (built-in)>, "_codecs": <module "_codecs" (built-in)>, "_frozen_importlib": <module "_frozen_importlib" (frozen)>, "encodings.aliases": <module "encodings.aliases" from "/usr/local/python35/lib/python3.5/encodings/aliases.py">, "abc": <module "abc" from "/usr/local/python35/lib/python3.5/abc.py">, "genericpath": <module "genericpath" from "/usr/local/python35/lib/python3.5/genericpath.py">, "_warnings": <module "_warnings" (built-in)>, "sysconfig": <module "sysconfig" from "/usr/local/python35/lib/python3.5/sysconfig.py">, "os": <module "os" from "/usr/local/python35/lib/python3.5/os.py">, "sre_compile": <module "sre_compile" from "/usr/local/python35/lib/python3.5/sre_compile.py">, "marshal": <module "marshal" (built-in)>, "readline": <module "readline" from "/usr/local/python35/lib/python3.5/lib-dynload/readline.cpython-35m-x86_64-linux-gnu.so">, "_sysconfigdata": <module "_sysconfigdata" from "/usr/local/python35/lib/python3.5/_sysconfigdata.py">, "copyreg": <module "copyreg" from "/usr/local/python35/lib/python3.5/copyreg.py">, "_sre": <module "_sre" (built-in)>, "sys": <module "sys" (built-in)>, "_weakref": <module "_weakref" (built-in)>, "_thread": <module "_thread" (built-in)>, "_signal": <module "_signal" (built-in)>, "_locale": <module "_locale" (built-in)>, "rlcompleter": <module "rlcompleter" from "/usr/local/python35/lib/python3.5/rlcompleter.py">, "_io": <module "io" (built-in)>, "errno": <module "errno" (built-in)>, "sre_constants": <module "sre_constants" from "/usr/local/python35/lib/python3.5/sre_constants.py">, "os.path": <module "posixpath" from "/usr/local/python35/lib/python3.5/posixpath.py">, "encodings.utf_8": <module "encodings.utf_8" from "/usr/local/python35/lib/python3.5/encodings/utf_8.py">, "posixpath": <module "posixpath" from "/usr/local/python35/lib/python3.5/posixpath.py">, "_weakrefset": <module "_weakrefset" from "/usr/local/python35/lib/python3.5/_weakrefset.py">, "site": <module "site" from "/usr/local/python35/lib/python3.5/site.py">, "_stat": <module "_stat" (built-in)>, "atexit": <module "atexit" (built-in)>, "_collections_abc": <module "_collections_abc" from "/usr/local/python35/lib/python3.5/_collections_abc.py">, "posix": <module "posix" (built-in)>, "sre_parse": <module "sre_parse" from "/usr/local/python35/lib/python3.5/sre_parse.py">, "__main__": <module "__main__" (built-in)>, "codecs": <module "codecs" from "/usr/local/python35/lib/python3.5/codecs.py">, "_frozen_importlib_external": <module "_frozen_importlib_external" (frozen)>}
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
>>> sys.path
["", "/usr/local/python35/lib/python35.zip", "/usr/local/python35/lib/python3.5", "/usr/local/python35/lib/python3.5/plat-linux", "/usr/local/python35/lib/python3.5/lib-dynload", "/usr/local/python35/lib/python3.5/site-packages"]
sys.platform 返回操作系统平台名称
>>> sys.platform
"linux"
sys.stdout 标准输出
#!/usr/bin/env python35
import sys
f = open("log.txt","a") #以追加的模式打开一个文件
__console__ = sys.stdout #备份默认console命令行
sys.stdout = f #指定标准输出到文件
print("hello python")
sys.stdout = __console__ #将标准输出改为模式的console命令行模式
print("hello world") #输出将会在console命令行下
[root@python python]# python35 stdout.py
hello world
[root@python python]# cat log.txt
hello python
sys.stderr 错误输出
-
sys.exc_info() 返回当前捕获的异常信息
-
sys.exec_prefix 返回平台独立的python文件安装的位置
>>> sys.exec_prefix
"/usr/local/python35"
sys.byteorder 本地字节规则的指示器,big-endian平台的值是”big”,little-endian平台的值是”little”
>>> sys.byteorder
"little"
sys.copyright 记录python版权相关的东西
>>> sys.copyright
"Copyright (c) 2001-2017 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved."
sys.api_version 解释器的C的API版本
>>> sys.api_version
1013