Python 当文件结构包含别名时子进程密码不一致

Python subprocess pwd inconsistent when file structure includes alias

当我运行下面的脚本

#!/usr/bin/env python
import subprocess
print(subprocess.check_output(["pwd"]))

结果是

/scratch1/name/Dropbox (NAM)/docs/research/Y2/results/s8

从我的 Ubuntu 终端,命令

pwd

产量

/quake/home/name/docs/research/Y2/results/s8

这是第一条路径的别名。为什么它们不一致?

TL;DR - 使用 os.getcwd()


您可以使用 os.path.realpath 将包含符号链接的路径转换为物理路径,解析任何符号链接:

~/src/Whosebug $ mkdir targetdir
~/src/Whosebug $ ln -s targetdir symlink
~/src/Whosebug $ cd symlink
~/src/Whosebug/symlink $
~/src/Whosebug/symlink $ python

>>> import os
>>> import subprocess
>>> import shlex
>>>
>>> path = subprocess.check_output('pwd').strip()
>>> path
'/Users/lukasgraf/src/Whosebug/symlink'
>>> os.path.realpath(path)
'/Users/lukasgraf/src/Whosebug/targetdir'

pwd 命令的 -P 选项也可以强制执行此操作。

来自 pwd 手册页(在 OS X 上):

The pwd utility writes the absolute pathname of the current working directory to the standard output.

Some shells may provide a builtin pwd command which is similar or identical to this utility. Consult the builtin(1) manual page.

 The options are as follows:

 -L      Display the logical current working directory.

 -P      Display the physical current working directory (all symbolic
         links resolved).

 If no options are specified, the -L option is assumed.

所以这也行得通:

>>> subprocess.check_output(shlex.split('pwd -P'))
'/Users/lukasgraf/src/Whosebug/targetdir\n'
>>>

但是,最好的选择是使用 Python 标准库中的 os.getcwd()

>>> os.getcwd()
'/Users/lukasgraf/src/Whosebug/targetdir'

它没有明确记录,但它似乎已经为您解析了符号链接。在任何情况下,您都希望避免对标准库已经为您提供的内容进行炮击(使用 subprocess),例如获取当前工作目录。