1. 程式人生 > >python 取得當前使用者的主目錄(sudo)

python 取得當前使用者的主目錄(sudo)

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


我的電腦Home目錄為 /home/wsh

 加入指令碼為evir.py

import os

if __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/wsh
wsh /home/wsh
wsh /home/wsh



2。 加上sudo指令


sudo  python envir.py



結果:
 
wsh /root
wsh /root
wsh /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: [email protected]