为什么shutil.copy()提出一个权限异常时cp不? [英] Why would shutil.copy() raise a permission exception when cp doesn't?

查看:2743
本文介绍了为什么shutil.copy()提出一个权限异常时cp不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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'

copy-test.py:

copy-test.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 是目录。

使用 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)

这篇关于为什么shutil.copy()提出一个权限异常时cp不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆