当 cp 没有时,为什么 shutil.copy() 会引发权限异常?

Why would shutil.copy() raise a permission exception when cp doesn#39;t?(当 cp 没有时,为什么 shutil.copy() 会引发权限异常?)

本文介绍了当 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() 会引发权限异常?

基础教程推荐