[英]Create broken symlink with Python
使用Python我想創建一個指向不存在的路徑的符號鏈接。 然而os.symlink只是抱怨“OSError:[Errno 2]沒有這樣的文件或目錄:”..這可以很容易地用ln程序完成,但是如何在不調用Python的ln程序的情況下在Python中完成它?
編輯: 不知怎的,我真的搞砸了這個:/ ...下面的兩個答案都是正確的
當您嘗試在不存在的目錄中創建符號鏈接時,會引發此類錯誤。 例如,如果/tmp/subdir
不存在,則以下代碼將失敗:
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)
為了創建符號鏈接,不需要存在該文件。 以下示例演示如何為不存在的文件創建符號鏈接:
首先,檢查/home/wieslander/tmp
是否沒有名為foobar
的文件:
[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar
ls: cannot access /home/wieslander/tmp/foobar: No such file or directory
創建一個名為brokensymlink
的符號鏈接,指向/home/wieslander/tmp/foobar
:
[wieslander@rizzo tmp]$ python
Python 2.5.2 (r252:60911, Sep 30 2008, 15:42:03)
[GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.symlink('/home/wieslander/tmp/foobar', 'brokensymlink')
檢查是否已創建符號鏈接且目標仍不存在:
[wieslander@rizzo tmp]$ ls -l brokensymlink
lrwxrwxrwx 1 wieslander wieslander 27 19 nov 13.13 brokensymlink -> /home/wieslander/tmp/foobar
[wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar
ls: cannot access /home/wieslander/tmp/foobar: No such file or directory
您確定要使用正確的參數調用符號鏈接嗎?
os.symlink('/usr/bin/python', 'python')
這應該在當前工作目錄中從python創建一個符號鏈接到/ usr / bin / python。
這可能是你的答案:
$ python
Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.symlink('/this/does/not/exist', 'broken')
>>> os.symlink('broken', '/this/does/not/exist')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory
你反駁了這些論點嗎? 或者您只是嘗試在不存在的目錄中創建符號鏈接?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.