无法在Windows上导入distutils.dir_util

14

我正在尝试在Windows 7 64位系统上使用distutils.dir_util。从我各种搜索中得到的信息来看,我可能需要单独安装一些distutils包?我确实有基本的distutils包可用,但它似乎被大幅简化和许多组件丢失。尝试研究distutils和windows总是引导我到Python构建脚本以及如何将distutils打包为可重新分发的Python项目或构建EXE文件,而这不是我感兴趣的。我只是无法确定从哪里获取这些代码。

虽然已经过了很长时间,但我想我是通过MSI安装程序安装Python的,不确定是否还有其他常见的方法。这是我的解释器输出:

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import distutils
>>> distutils.dir_util
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'dir_util'

好的,看起来可以使用以下代码实现:

Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import distutils.core
>>> distutils.dir_util
<module 'distutils.dir_util' from 'C:\apps\Python27\lib\distutils\dir_util.pyc'>

有没有人能解释一下为什么需要这种方法,或者它是如何工作的?


http://stackoverflow.com/a/19106359/67824 - Ohad Schneider
1
我发现那个答案不完整,所以我在这里回答了它。 - kmarsh
1个回答

28

在我手头能够使用的最老版本2.7.5上,以下方法对我有效:

    #Both imports are needed to avoid errors
    import distutils
    from distutils import dir_util

    distutils.dir_util.copy_tree("./foo", "./bar")
如果我忽略了“import distutils”,我会收到错误信息:

NameError: name 'distutils' is not defined

如果我省略了“from import”,则会出现以下错误:

AttributeError: 'module' object has no attribute 'dir_util'

针对你提出的最后一个问题,我只能猜测开发人员可能想要隐藏distutils导入的大部分内容,出于尺寸/空间/效率等方面的考虑。

6
奇怪!在Python 3.6.4上对我来说也是一样的。 - Prof. Falken
3
同样适用于Python 3.5.2版本。 - D_K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接