使用 Python 创建损坏的符号链接 [英] Create broken symlink with Python

查看:34
本文介绍了使用 Python 创建损坏的符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Python 我想创建一个指向不存在路径的符号链接.然而 os.symlink 只是抱怨OSError: [Errno 2] No such file or directory:".. 这可以用 ln 程序轻松完成,但是如何在 Python 中做到这一点而不调用ln Python 程序?

Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?

不知何故,我真的搞砸了:/...下面的两个答案都是正确的

推荐答案

当您尝试在不存在的目录中创建符号链接时,会引发此类错误.例如,如果 /tmp/subdir 不存在,以下代码将失败:

Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:

os.symlink('/usr/bin/python', '/tmp/subdir/python')

但这应该会成功运行:

src = '/usr/bin/python'
dst = '/tmp/subdir/python'

if not os.path.isdir(os.path.dirname(dst)):
    os.makedirs(os.path.dirname(dst))
os.symlink(src, dst)

这篇关于使用 Python 创建损坏的符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆