使用pathlib获取当前的符号目录

时间:2018-12-11 20:17:07

标签: python-3.x

在符号目录中执行Python 3脚本时,我想获取当前目录的未引用路径。但是,pathlib的默认行为返回取消引用的路径:

 $ mkdir test1
 $ ln -s test1 test2
 $ cd test2
 $ pwd
/home/myuser/test2
$ ipython3
Python 3.7.0 (default, Oct  9 2018, 10:31:47) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from pathlib import Path                                                                                                                  

In [2]: str(Path.cwd())                                                                                                                                
/home/myuser/test1

我想要的行为是获取“ / home / myuser / test2”,因为这是执行“脚本”(在这种情况下为解释器)的位置,最好使用pathlib

1 个答案:

答案 0 :(得分:1)

使用os.getenv('PWD')

目录:

$ ls -l
total 1
drwxr-xr-x+ 1 cody agroup 0 Dec 11 15:23 dir1
lrwxrwxrwx  1 cody agroup 4 Dec 11 15:23 dir2 -> dir1

dir2的结果:

>>> str(Path.cwd())
'/home/cody/so/dir1'
>>> os.getenv('PWD')
'/home/cody/so/dir2'