python 取得当前用户的主目录(sudo)

来源:互联网 发布:java生成mysql临时表 编辑:程序博客网 时间:2024/04/29 22:14

'sudo' changes enviroment variables ,such as : os.environ['HOME'], etc


我的电脑Home目录为 /home/wsh

 加入脚本为evir.py

import osif __name__ == "__main__":     print 'wsh'+os.environ['HOME']    print 'wsh'+ os.path.expandvars('$HOME')    print 'wsh'+ os.path.expanduser('~')



执行此脚本。有两种结果


执行此脚本。有两种结果

1 。 直接执行 treminal 输入:

python envir.py




结果:


wsh /home/wshwsh /home/wshwsh /home/wsh



2。 加上sudo指令


sudo  python envir.py



结果:
 
wsh /rootwsh /rootwsh /root


so just use:

os.getlogin()

in conclusion:

  if you want to get current user home  in linux , while you have to get 'sudo' permission. that is to say . you need sudo to start up your python script.

just use "os.getlogin()", since other commands are changed because of sudo. then use can just to get current home directory use:

'/home/'+os.getlogin()



author:  wsh

emiail: tongzhuodenilove@163.com

0 0
原创粉丝点击