class - os

最後更新: 2016-07-25

目錄

  • name (OS 的類型)
  • uname (Kernel Version)
  • environ (Environment Variables)
  • Path (同 path 有關的)
  • File Operations
  • system (run cli)
  • uid, gid

 


Usage

import os

name

os.name

posix

os.uname()

('Linux', 'webpy', '3.2.0-4-686-pae', '#1 SMP Debian 3.2.51-1', 'i686')

environ

Syntax: os.getenv(varname[, value])

i.e.

os.environ

{'LANG': 'en_HK.UTF-8', ...
'PWD': '/home/tim/cms' ...

os.getenv('HOME')

'/root'

 


Path

 

os.getcwd()

在那裡執行 script. 不等於 script 的位置

os.chdir(path)

os.path.realpath(FILE)

獲得 FILE 的所在位置

scriptpath = os.path.dirname(os.path.realpath(__file__))

os.path.abspath()

current_dir = os.path.abspath(os.path.dirname(__file__))

os.path.abspath:

Return a normalized absolutized version of the pathname path.

os.path.basename()

file_name = os.path.abspath(os.path.basename(__file__))

__file__                                   # Full Path: /roottest.py
os.path.basename(__file__)      # test.py

parent_dir

parent_dir = os.path.abspath(current_dir + "/../")

os.path.exists(path)

Return True if path refers to an existing path.

Returns False for broken symbolic links.

os.path.getmtime(path)

最後修改時間

1665026831.13

os.path.getsize(path)

# Unit: byte

8388608

 


File Operations

 

# remove file

os.remove("demofile.txt")

 


system

 

Execute the command (a string) in a subshell.

Clear Console Scressn

os.system('clear')

 


UID & GID

 

os.getuid()

os.getgid()

 


 

 

 

Creative Commons license icon Creative Commons license icon