为什么 ln from Python subprocess 在正常命令行成功时失败?

Why does ln from Python subprocess fail while it succeeds from normal command line?

正如标题所说:

>>> from subprocess import check_output
>>> check_output(['ln', '~/other_folder/src/models/sc_models.py', './src/models/sc_models.py'])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command '['ln', '~/other_folder/src/models/sc_models.py', './src/models/sc_models.py']' returned non-zero exit status 1
>>> exit()
$ ln ~/other_folder/src/models/sc_models.py ./src/models/sc_models.py
$

怎么会这样?它如何从命令行成功,但从 Python 子进程调用失败?

欢迎所有提示!

您需要使用 os.path.expanduser:

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

import os

os.path.expanduser('~/other_folder/src/models/sc_models.py')

In [2]: os.path.expanduser("~")
Out[2]: '/home/padraic'

Python 正在您的 cwd 中寻找名为 ~ 的目录,这显然失败了。当您 运行 来自 bash 的代码被扩展时, ~ 被扩展,除非您使用 shell=True 将命令传递给 shell 和 shell 会扩展波浪号,然后您需要使用 os.path.expanduser 或传递整个路径,即 /home/user/other_folder ......我会坚持使用 shell=False 和 os.path.expanduser("~").