Silent os.rename failure

时间:2015-07-28 16:44:58

标签: python linux

Let's say I have two files which are hardlinked to each other:

-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 bar
-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 foo

Then, I run this in python:

>>> import os
>>> os.rename('foo', 'bar')

I get no errors. But, listing the directory again, I still see foo.

-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 bar
-rw-rw-r-- 2 mparrott grp 5 Jul 28 09:38 foo

It seems like this is happening because the files are indeed the same file (inode). However, I would still expect foo to be removed or an error to be raised.

Does anyone know why this is failing silently? My question is about the implementation itself rather than how to work around the problem (which I did using os.path.samefile). I'm on rhel 6.4.

Thanks!

1 个答案:

答案 0 :(得分:3)

Python's os.rename function simply performs the rename system call. If the source and target are the same file, the system call does nothing silently. I get the same result as your Python script if I run the C program:

#include <stdio.h>

int main() {
    int result = rename("foo", "bar");
    printf("result = %d\n", result);
}

This prints result = 0 and leaves both files.

This behavior is documented in the Linux man page:

If oldpath and newpath are existing hard links referring to the same file, then rename() does nothing, and returns a success status.

This is also specified in POSIX:

If the old argument and the new argument resolve to the same existing file, rename() shall return successfully and perform no other action.