質問
場合に呼びかけ os.stat()
に破 symlink
, pythonスローする OSError
ます。これはとても便利です。しかし、いくつかの他の理由 os.stat()
が投同様の例外です。はあるのでより精度の検切れ symlinks
Python Linux?
解決
共通のPython言うことをやりながらお寛容による。がんのファンにこの声明の実生活での限りではないか。通常は避けたいという思いるコードチェーン二つのシステム呼び出しと同じファイルで使いのファイルとの間で二つの通話にコードです。
典型的な間違いは、シンプルにわかりやすく書くように:
if os.path.exists(path):
os.unlink(path)
第二話(os.リンクを解除)に失敗する場合があり何かを削除すれば御試験を例外停止の機能から。(と思いますがそのようなことはなにがしかな漁業を行うバグのようにそのコードベースの最終週は、そのようなバグが左数のプログラマ引掻本願'Heisenbug'最後の数ヶ月)
で、特定のケースでは、だらだらとい:
try:
os.stat(path)
except OSError, e:
if e.errno == errno.ENOENT:
print 'path %s does not exist or is a broken symlink' % path
else:
raise e
の悩みには、statを返します同じエラーコードシンボリックリンクするだけなんじゃない、壊れたシンボリックリンク.
なので、しょうがないの選択により、atomicity、次のように
if not os.path.exists(os.readlink(path)):
print 'path %s is a broken symlink' % path
他のヒント
os.lstat() が有効なことがあります。まlstat()が成功しstat()に失敗した場合、それはあるんじゃないでしょうか折します。
これは原子力でも動きます。
os.path.islink(filename) and not os.path.exists(filename)
実際に RTFM (読書のマニュアル)において
os.ます。が存在する(パス)
場合にTrueを返しますパスは、既存のパスです。Falseを返します壊れたシンボリックリンク.
でも言うのです:
プラットフォームによっては、この機能がFalseを返す場合は許可されていないため実行します。stat()に要求されたファイルの場合でもパス物理的に存在します。
だが気になアクセス権を追加してくださいその他の条項.
できるだ試験hardlinksなpython?/bin/試験のFILE1-ef FILE2ることを条件がtrueの時にファイル共有inode.
このようなもの find . -type f -exec test \{} -ef /path/to/file \; -print
作品のためのハードリンクの試験は特定のファイルです。
るっ読む man test
に記載の -L
や -h
る作業を一つのファイルの場合にtrueを返しますこのファイルがシンボリックリンクしない場合は、対象者が欠けています。
見つかる head -0 FILE1
り戻すことの出口コード 0
の場合はファイルを開き、 1
できない場合は、の場合へのシンボリックリンクの普通のファイル作品としての試験のためのかどうかの目標を読み取ることができます。
てみるのも良いでしょうを使用realpath()へのポイントシンボリックリンク、そしているかどうかを判断するための有効なファイルの利用はお断りすることがあります。
なるだけでなくその瞬間がありますので,そこでしっかりで遊ぶので、見ていただくもの)
したらいいと思います。pythonガのようにも見えます。readlink()?ロジック混雑して待たされることにperlを使用readlink()を対象にstat()の試合の目標が存在します。
編集:い叩きあperlるデモreadlink.と思うのperlのstat、readlinkやpythonのos.stat()やos.readlink()は両方のラッパーのためのシステム呼び出し、この翻訳の合理的なものの概念実証コード:
wembley 0 /home/jj33/swap > cat p
my $f = shift;
while (my $l = readlink($f)) {
print "$f -> $l\n";
$f = $l;
}
if (!-e $f) {
print "$f doesn't exist\n";
}
wembley 0 /home/jj33/swap > ls -l | grep ^l
lrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -> non-existant-file
lrwxrwxrwx 1 root users 31 Oct 10 2007 mm -> ../systems/mm/20071009-rewrite//
lrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -> mm/
wembley 0 /home/jj33/swap > perl p mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p mmm
mmm -> mm
mm -> ../systems/mm/20071009-rewrite/
wembley 0 /home/jj33/swap > perl p link
link -> non-existant-file
non-existant-file doesn't exist
wembley 0 /home/jj33/swap >
また同様の問題:かく破symlinks場合でも起こるも親dir?たいという思いもありましたログインすべてに申請を取り扱うかなり大きなファイル数が多すぎを繰り返します。
ここでは私た、ユニット。
fileutil.py:
import os
from functools import lru_cache
import logging
logger = logging.getLogger(__name__)
@lru_cache(maxsize=2000)
def check_broken_link(filename):
"""
Check for broken symlinks, either at the file level, or in the
hierarchy of parent dirs.
If it finds a broken link, an ERROR message is logged.
The function is cached, so that the same error messages are not repeated.
Args:
filename: file to check
Returns:
True if the file (or one of its parents) is a broken symlink.
False otherwise (i.e. either it exists or not, but no element
on its path is a broken link).
"""
if os.path.isfile(filename) or os.path.isdir(filename):
return False
if os.path.islink(filename):
# there is a symlink, but it is dead (pointing nowhere)
link = os.readlink(filename)
logger.error('broken symlink: {} -> {}'.format(filename, link))
return True
# ok, we have either:
# 1. a filename that simply doesn't exist (but the containing dir
does exist), or
# 2. a broken link in some parent dir
parent = os.path.dirname(filename)
if parent == filename:
# reached root
return False
return check_broken_link(parent)
ユニット試験:
import logging
import shutil
import tempfile
import os
import unittest
from ..util import fileutil
class TestFile(unittest.TestCase):
def _mkdir(self, path, create=True):
d = os.path.join(self.test_dir, path)
if create:
os.makedirs(d, exist_ok=True)
return d
def _mkfile(self, path, create=True):
f = os.path.join(self.test_dir, path)
if create:
d = os.path.dirname(f)
os.makedirs(d, exist_ok=True)
with open(f, mode='w') as fp:
fp.write('hello')
return f
def _mklink(self, target, path):
f = os.path.join(self.test_dir, path)
d = os.path.dirname(f)
os.makedirs(d, exist_ok=True)
os.symlink(target, f)
return f
def setUp(self):
# reset the lru_cache of check_broken_link
fileutil.check_broken_link.cache_clear()
# create a temporary directory for our tests
self.test_dir = tempfile.mkdtemp()
# create a small tree of dirs, files, and symlinks
self._mkfile('a/b/c/foo.txt')
self._mklink('b', 'a/x')
self._mklink('b/c/foo.txt', 'a/f')
self._mklink('../..', 'a/b/c/y')
self._mklink('not_exist.txt', 'a/b/c/bad_link.txt')
bad_path = self._mkfile('a/XXX/c/foo.txt', create=False)
self._mklink(bad_path, 'a/b/c/bad_path.txt')
self._mklink('not_a_dir', 'a/bad_dir')
def tearDown(self):
# Remove the directory after the test
shutil.rmtree(self.test_dir)
def catch_check_broken_link(self, expected_errors, expected_result, path):
filename = self._mkfile(path, create=False)
with self.assertLogs(level='ERROR') as cm:
result = fileutil.check_broken_link(filename)
logging.critical('nothing') # trick: emit one extra message, so the with assertLogs block doesn't fail
error_logs = [r for r in cm.records if r.levelname is 'ERROR']
actual_errors = len(error_logs)
self.assertEqual(expected_result, result, msg=path)
self.assertEqual(expected_errors, actual_errors, msg=path)
def test_check_broken_link_exists(self):
self.catch_check_broken_link(0, False, 'a/b/c/foo.txt')
self.catch_check_broken_link(0, False, 'a/x/c/foo.txt')
self.catch_check_broken_link(0, False, 'a/f')
self.catch_check_broken_link(0, False, 'a/b/c/y/b/c/y/b/c/foo.txt')
def test_check_broken_link_notfound(self):
self.catch_check_broken_link(0, False, 'a/b/c/not_found.txt')
def test_check_broken_link_badlink(self):
self.catch_check_broken_link(1, True, 'a/b/c/bad_link.txt')
self.catch_check_broken_link(0, True, 'a/b/c/bad_link.txt')
def test_check_broken_link_badpath(self):
self.catch_check_broken_link(1, True, 'a/b/c/bad_path.txt')
self.catch_check_broken_link(0, True, 'a/b/c/bad_path.txt')
def test_check_broken_link_badparent(self):
self.catch_check_broken_link(1, True, 'a/bad_dir/c/foo.txt')
self.catch_check_broken_link(0, True, 'a/bad_dir/c/foo.txt')
# bad link, but shouldn't log a new error:
self.catch_check_broken_link(0, True, 'a/bad_dir/c')
# bad link, but shouldn't log a new error:
self.catch_check_broken_link(0, True, 'a/bad_dir')
if __name__ == '__main__':
unittest.main()