From 145155140f4f25870b2fb832c4b781bb76a48cff Mon Sep 17 00:00:00 2001 From: lkk7 Date: Sun, 26 Jul 2026 11:47:45 +0200 Subject: [PATCH] gh-154726: Fix `shutil.copyfile()` for device symlinks with `follow_symlinks=False` --- Lib/shutil.py | 5 ++++- Lib/test/test_shutil.py | 13 +++++++++++++ .../2026-07-26-11-45-34.gh-issue-154726.hLJk5-.rst | 3 +++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-07-26-11-45-34.gh-issue-154726.hLJk5-.rst diff --git a/Lib/shutil.py b/Lib/shutil.py index 6a2e2b2ffdae2c..94617ec296f508 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -292,8 +292,11 @@ def copyfile(src, dst, *, follow_symlinks=True): if _samefile(src, dst): raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) + copy_symlink = not follow_symlinks and _islink(src) file_size = 0 for i, fn in enumerate([src, dst]): + if copy_symlink and i == 0: + continue try: st = _stat(fn) except OSError: @@ -315,7 +318,7 @@ def copyfile(src, dst, *, follow_symlinks=True): if _WINDOWS and i == 0: file_size = st.st_size - if not follow_symlinks and _islink(src): + if copy_symlink: os.symlink(os.readlink(src), dst) else: with open(src, 'rb') as fsrc: diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index 6832bea094fc1d..bbbd0ca66edb7f 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -1583,6 +1583,19 @@ def test_copyfile_character_device(self): self.assertRaisesRegex(shutil.SpecialFileError, 'is a character device', shutil.copyfile, src_file, '/dev/null') + @os_helper.skip_unless_symlink + @unittest.skipUnless(os.path.exists('/dev/null'), 'requires /dev/null') + def test_copyfile_symlink_to_character_device(self): + tmp_dir = self.mkdtemp() + src = os.path.join(tmp_dir, 'src') + dst = os.path.join(tmp_dir, 'dst') + os.symlink('/dev/null', src) + + shutil.copyfile(src, dst, follow_symlinks=False) + + self.assertTrue(os.path.islink(dst)) + self.assertEqual(os.readlink(dst), '/dev/null') + def test_copyfile_block_device(self): block_dev = None for dev in ['/dev/loop0', '/dev/sda', '/dev/vda', '/dev/disk0']: diff --git a/Misc/NEWS.d/next/Library/2026-07-26-11-45-34.gh-issue-154726.hLJk5-.rst b/Misc/NEWS.d/next/Library/2026-07-26-11-45-34.gh-issue-154726.hLJk5-.rst new file mode 100644 index 00000000000000..73cf40a7207743 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-26-11-45-34.gh-issue-154726.hLJk5-.rst @@ -0,0 +1,3 @@ +Fix :func:`shutil.copyfile` to copy a symbolic link to a special file when +``follow_symlinks=False`` instead of raising +:exc:`~shutil.SpecialFileError`.