Python os 模块

Python OS 模块提供简单的功能,使我们能够互动并获取操作系统信息,甚至控制流程。

Python 模块

操作系统模块提供的功能使我们能够操作基本操作系统任务,无论它是Windows平台,Macintosh或Linux。

Python 导入 OS

Please note that first of all we have to import OS module in our program, then only we can execute any of it's functions. python os import, python os module

姓名 姓名

这个函数给了它导入的操作系统模块的名称。这取决于底层操作系统而有所不同。目前,它注册了posix,os2,ce,nt,riscosjava

1>>> print(os.name)
2posix

显然,这可以根据口译器输出不同的平台。

周围

‘environ’不是一个函数,而是一个过程参数,通过它我们可以访问系统的环境变量。

1import os
2output = os.environ['HOME']
3print(output)

When we run this script, the following will be the output: python os environment variable We can use it to work with the environment variables, read more at Python set environment variable.

「execvp」函数是在系统上运行其他命令的一种方式,让我们来看看这个函数的示例代码片段:

1import os
2program = "python"
3arguments = ["hello.py"]
4print(os.execvp(program, (program,) +  tuple(arguments)))

为此,我们刚刚创建了一个样本脚本,例如hello.py,并使用以下代码:

1print('Hello')

When we run this script, the following will be the output: python os module, python os execute other script

此 OS 模块函数返回当前流程的用户 ID 或 UID,正如人们所知的那样。

1>>> os.getuid()
2501

因此,当前的壳过程 ID 是 501。

名称: rename

借助 Python OS 重命名函数,我们可以轻松地重命名文件。

1import os
2fileDir = "JournalDev.txt"
3os.rename(fd,'JournalDev_Hi.txt')

请注意,为此,我们必须为我们的脚本提供正确的权限。

系统 系统

Python OS 系统功能允许我们在 Python 脚本中运行一个命令,就像我在我的壳中运行它一样。

1import os
2currentFiles = os.system("users > users.txt")

When I ran this script, a new file was made in the same directory with name users.txt and content String as 'shubham' as this is returned by original shell as well: Python OS System command Note that this is a very powerful command and should be used cautiously.

错误 错误

Python os 模块错误类是 I/O 相关错误的基本类,因此我们可以使用 OSError 来捕捉 IO 错误。

1import os
2
3try:
4    f = open('abc.txt', 'r')  # file is missing
5except OSError:
6    print('Error')

此函数返回当前的进程 ID 或 PID,正如人们所知道的那样。

1>>> os.getpid()
271622

因此,当前壳流程的用户 ID 是 71622。

名单 名单

此函数仅列出了当前工作目录中存在的文件和目录。

1>>> import os
2>>> os.listdir()
3['.DS_Store', '.localized', 'JournalDev', 'Java', 'Python']

返回可迭代的目录和文件名单列表。

欧盟

此函数返回识别当前操作系统所执行的信息。

1>>> os.uname()
2posix.uname_result(sysname='Darwin', nodename='Shubham.local', release='17.2.0', version='Darwin Kernel Version 17.2.0: Fri Sep 29 18:27:05 PDT 2017; root:xnu-4570.20.62~3/RELEASE_X86_64', machine='x86_64')

实际上,这是一个精确的细节。

导入 OS.Path 导入 OS

os.path实际上很奇怪,它看起来像是os包装了子模块path,但实际上,os是一个正常的模块,它与sys.module一起工作以支持os.path

当 Python 启动时,它会将许多模块加载到 sys.module

  • 当 Python 启动时, os 模块也会加载。

摘要

在本课中,我们阅读了在Python中OS模块提供的各种功能,并看到它们是如何工作的。 查看更多关于Python的教训(/community/tutorials/python-tutorial)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus