文件对象的绝对路径

发布于 2024-08-25 18:36:55 字数 578 浏览 5 评论 0原文

之前已经在 StackOverflow 上讨论过这个问题 - 我正在尝试找到一种找到文件对象的绝对路径的好方法,但我需要它对 os.chdir() 具有鲁棒性,因此无法使用

f = file('test')
os.path.abspath(f.name)

相反,我想知道以下是否是一个好的解决方案 - 基本上扩展文件类,以便在打开时保存文件的绝对路径:

class File(file):

    def __init__(self, filename, *args, **kwargs):
        self.abspath = os.path.abspath(filename)
        file.__init__(self, filename, *args, **kwargs)

然后可以

f = File('test','rb')
os.chdir('some_directory')
f.abspath # absolute path can be accessed like this

做 这样做有任何风险吗?

This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use

f = file('test')
os.path.abspath(f.name)

Instead, I was wondering whether the following is a good solution - basically extending the file class so that on opening, the absolute path of the file is saved:

class File(file):

    def __init__(self, filename, *args, **kwargs):
        self.abspath = os.path.abspath(filename)
        file.__init__(self, filename, *args, **kwargs)

Then one can do

f = File('test','rb')
os.chdir('some_directory')
f.abspath # absolute path can be accessed like this

Are there any risks with doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌路终见情 2024-09-01 18:36:55

一个重大风险是,一旦文件打开,进程就会通过文件描述符而不是路径来处理该文件。在许多操作系统上,文件的路径可以被其他进程更改(例如,通过不相关进程中的 mv 操作),并且文件描述符仍然有效并引用到同一个文件。

我经常利用这一点,例如,开始下载一个大文件,然后意识到目标文件不是我想要的位置,然后跳到一个单独的 shell 并将其移动到正确的位置 – 而下载继续不间断。

因此,当操作系统没有提供这样的保证时,在进程的生命周期中依赖路径保持不变是一个坏主意。

One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, not its path. On many operating systems, the file's path can be changed by some other process (by a mv operation in an unrelated process, say) and the file descriptor is still valid and refers to the same file.

I often take advantage of this by, for example, beginning a download of a large file, then realising the destination file isn't where I want it to be, and hopping to a separate shell and moving it to the right location – while the download continues uninterrupted.

So it is a bad idea to depend on the path remaining the same for the life of the process, when there's no such guarantee given by the operating system.

莳間冲淡了誓言ζ 2024-09-01 18:36:55

这取决于你需要它做什么。

只要您了解限制(有人可能会在此期间移动、重命名或硬链接文件),就有很多适当的用途。当你完成文件或者在写入文件时出现问题时,你可能想删除该文件(例如,gcc 在写入文件时执行此操作):

f = File(path, "w+")
try:
    ...
except:
    try:
        os.unlink(f.abspath)
    except OSError: # nothing we can do if this fails
        pass
    raise

如果你只是想能够在用户消息中识别该文件,那么已经有文件名。不幸的是,不可能(可靠地)将其用于其他用途;例如,无法区分文件名“”和 sys.stdin。

(你真的不应该从内置类派生只是为了向它添加属性;这只是 Python 的一个丑陋的不一致的怪癖......)

It depends on what you need it for.

As long as you understand the limitations--someone might move, rename, or hard-link the file in the interim--there are plenty of appropriate uses for this. You may want to delete the file when you're done with it or if something goes wrong while writing it (eg. gcc does this when writing files):

f = File(path, "w+")
try:
    ...
except:
    try:
        os.unlink(f.abspath)
    except OSError: # nothing we can do if this fails
        pass
    raise

If you just want to be able to identify the file in user messages, there's already file.name. It's impossible to use this (reliably) for anything else, unfortunately; there's no way to distinguish between a filename "<stdin>" and sys.stdin, for example.

(You really shouldn't have to derive from a builtin class just to add attributes to it; that's just an ugly inconsistent quirk of Python...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文