【问题标题】:Appending Pythonpath, importing modules from different directories on windows附加Pythonpath,从windows不同目录导入模块
【发布时间】:2016-07-09 02:40:04
【问题描述】:

我一直在使用 Learn Python The Hard Way,但我被困在示例 48 中。在示例 47 中,我必须创建如下所示的目录:

skeleton
|--ex47
   |--module.py
   |--__init__.py
|--tests
   |--ex47_tests.py
   |--__init__.py

从现在开始,我必须将 ex47/module.py 导入到 tests/ex47_tests.py 中。我收到“没有名为 ex47 的模块”错误。这个问题的解决方案是通过在module.py中添加两行代码来将ex47目录的路径添加到站点包中:

import sys
sys.path.append('./ex47')

这很好用。我可以将 module.py 导入到 ex47_tests.py,然后我可以将它导入到我计算机上的任何位置。

转到示例 48 后,我创建了完全相同的目录、文件,并添加了 ex48/ 的路径,并且一直收到 'No module named 48'。我在互联网上搜索了不同的解决方案,它们都不起作用。将__init__.py 添加到骨架中没有帮助。

这个问题是超级基础的事情,但是它不介绍给新的python程序员。 顺便说一句,我想要一个可以在任何可以使用我的代码的计算机上运行的解决方案。

Linux 中是否会出现此类问题?

【问题讨论】:

    标签: python windows import python-3.4 pythonpath


    【解决方案1】:

    所有你需要看到的是你从哪里调用 python 程序。 我有以下文件。

    C:\Users\kumarvivek\Desktop>tree /f skeleton
    Folder PATH listing for volume ????
    Volume serial number is 6AE1-4919
    C:\USERS\KUMARVIVEK\DESKTOP\SKELETON
    │   __init__.py
    │
    ├───ex47
    │       mod.py
    │       mod.pyc
    │       __init__.py
    │       __init__.pyc
    │
    └───tests
            ex47_tests.py
            __init__.py
    
    
    C:\Users\kumarvivek\Desktop>
    

    内容如下:

    C:\Users\kumarvivek\Desktop>type skeleton\ex47\mod.py
    import os
    x = "C:\\Users\\kumarvivek\\Desktop\\skeleton\\ex47\\module.py"
    directoryPath= os.path.dirname(x)
    fileName = os.path.basename(x)
    print "\nFilePath:      %s\nDirectoryPath: %s\nFileName:      %s\n" %(x, directo
    ryPath, fileName)
    C:\Users\kumarvivek\Desktop>
    

    还有

    import sys
    
    # If the Current Working directory is skeleton
    # C:\Users\kumarvivek\Desktop\skeleton>python C:\Users\kumarvivek\Desktop\skeleton\tests\ex47_tests.py
    #
    # sys.path.append(r"..\skeleton")
    
    # If the Current Working directory is any of these "tests" or "ex47"
    # C:\Users\kumarvivek\Desktop\skeleton\tests>python C:\Users\kumarvivek\Desktop\skeleton\tests\ex47_tests.py
    # C:\Users\kumarvivek\Desktop\skeleton\ex47>
    #
    # sys.path.append(r"..\..\skeleton")
    
    sys.path.append(r"..\..\skeleton")
    
    
    from ex47 import mod
    
    print mod.x , mod.directoryPath, mod.fileName
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      • 2015-12-23
      • 2017-10-11
      • 1970-01-01
      • 2022-08-16
      相关资源
      最近更新 更多