25

我确定这是故意的,所以有人可以解释这种行为的理由:

Python 2.7.2 (default, Oct 13 2011, 15:27:47) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os.path import isdir,expanduser
>>> isdir("~amosa/pdb")
False
>>> isdir(expanduser("~amosa/pdb"))
True
>>>
>>> from os import chdir
>>> chdir("~amosa/pdb")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '~amosa/pdb'
>>> chdir(expanduser("~amosa/pdb"))
>>>

这真的很烦人,因为毕竟可以明确解析其中包含用户名的路径......我想编写可以处理用户可能给我的任何类型输入的代码,但是这种行为需要我调用 expanduser我的代码必须处理的每条路径。这也意味着在我打印出该路径供用户查看的任何地方,它的可读性都会比他们给我的略差。

这似乎与“鸭子打字”的概念不一致,我概括地说我希望python不会对我发牢骚,除非真的有问题......

4

2 回答 2

26

因为底层系统调用不能识别用户路径,并且文件访问 API 是对它们的一个相当薄的包装器。

此外,对于非 Unix 用户来说,
如果(例如)fopen("~foo")返回“foo: no such user”错误("~foo"例如 Windows 上的有效文件名) ,这将是相当令人惊讶的......<br> 或者,类似地,如果fopen("~administrator")返回类似“是目录:C:\Documents and Settings\Administrator\”的错误。

最后,正如评论者所指出的:您将“鸭子打字”与“有用的快捷方式”混淆了,这是两个完全不同的东西:
- 鸭子打字允许我用任何像鸭子一样嘎嘎叫的东西代替鸭子。
- 有用的快捷方式让我可以用任何可以让它像鸭子一样嘎嘎叫的东西来代替鸭子。(Python 不像其他一些语言那样“试图让它嘎嘎”)。

于 2012-05-07T19:25:01.773 回答
11

在普通的 Unix 实用程序中,~amosa语法由 shell 处理,shell 是调用实用程序的程序。实用程序本身不知道特殊~语法(通常)。

因此,如果您的 python 程序被 Unix 上的 shell 调用,它将正常工作:

$ python -c 'import sys; print sys.argv[1]' ~drj
/home/drj

Notice how the python program above prints the expanded path, even though it clearly has no code to do the expansion itself. The shell expanded it.

于 2014-07-15T18:58:33.657 回答