Why would shutil.copy() raise a permission exception when cp doesn#39;t?(当 cp 没有时,为什么 shutil.copy() 会引发权限异常?)
问题描述
shutil.copy() 引发权限错误:
shutil.copy() is raising a permissions error:
Traceback (most recent call last):
File "copy-test.py", line 3, in <module>
shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images')
File "/usr/lib/python2.7/shutil.py", line 118, in copy
copymode(src, dst)
File "/usr/lib/python2.7/shutil.py", line 91, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif'
复制测试.py:
import shutil
shutil.copy('src/images/ajax-loader-000000-e3e3e3.gif', 'bin/styles/blacktie/images')
我正在从命令行运行 copy-test.py:
I am running copy-test.py from the command line:
python copy-test.py
但是从命令行对同一文件运行 cp 到同一目的地不会导致错误.为什么?
But running cp from the command line on the same file to the same destination doesn't cause an error. Why?
推荐答案
失败的操作是chmod,而不是副本本身:
The operation that is failing is chmod, not the copy itself:
File "/usr/lib/python2.7/shutil.py", line 91, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'bin/styles/blacktie/images/ajax-loader-000000-e3e3e3.gif'
这表明该文件已经存在并且由另一个用户拥有.
This indicates that the file already exists and is owned by another user.
shutil.copy 已指定复制权限位.如果您只想复制文件内容,请使用 shutil.copyfile(src, dst) 或 shutil.copyfile(src, os.path.join(dst, os.path.basename(src))) 如果 dst 是一个目录.
shutil.copy is specified to copy permission bits. If you only want the file contents to be copied, use shutil.copyfile(src, dst), or shutil.copyfile(src, os.path.join(dst, os.path.basename(src))) if dst is a directory.
一个与 dst 一起工作的函数,无论是文件还是目录,并且不复制权限位:
A function that works with dst either a file or a directory and does not copy permission bits:
def copy(src, dst):
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
shutil.copyfile(src, dst)
这篇关于当 cp 没有时,为什么 shutil.copy() 会引发权限异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当 cp 没有时,为什么 shutil.copy() 会引发权限异常?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
