Press "Enter" to skip to content

python读取系统信息

python读取系统信息的一些方法

最主要是的platform模块:

>>> import platform
>>> platform.version()
'#1 SMP Fri Feb 22 00:31:26 UTC 2013'
>>> platform.platform()
'Linux-2.6.32-358.el6.x86_64-x86_64-with-centos-6.4-Final'
>>> platform.system()
'Linux'
>>> platform.machine()
'x86_64'
>>> platform.python_build()
('r266:84292', 'Feb 22 2013 00:00:18')
>>> platform.python_version()
'2.6.6'
>>> platform.release()
'2.6.32-358.el6.x86_64'
>>> platform.uname()
('Linux', 'localhost.localdomain', '2.6.32-358.el6.x86_64', '#1 SMP Fri Feb 22 00:31:26 UTC 2013', 'x86_64', 'x86_64')
>>> platform.architecture()
('64bit', 'ELF')
在windows上,专门还有个platform.win32_ver() 可用

获取用户名:

>>> import getpass 
>>> getpass.getuser() 
'root'

获取环境变量:

>>> import os
>>> import pwd
>>> os.environ['LANG']
'en_US.UTF-8'
>>> print os.getenv('LANG')
en_US.UTF-8
>>> print os.getenv('PWD')
/root
>>> print os.getenv('HOME')
/root
>>> print os.getenv('USER')
root
>>> print os.getenv('HOSTNAME')
localhost.localdomain
>>> print os.getenv('SHELL')
/bin/bash
>>> pwd.getpwuid(os.getuid())
pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')
>>> pwd.getpwuid(os.getuid())[0]  #获得用户名
'root'
>>> pwd.getpwuid(os.getuid())[5]  #获得家目录
'/root'
>>> pwd.getpwuid(os.getuid())[6]  #获得shell
'/bin/bash'
还有个os.environ.get,会返回所有环境变量为一个字典
Leave a Reply

Your email address will not be published. Required fields are marked *