Skip to main content
 首页 » 编程设计

python之为什么来自 Python 子进程的 ln 在正常命令行成功时失败

2025年05月04日1598°冷暖

正如标题所说:

>>> 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("~").