zoukankan      html  css  js  c++  java
  • python绝对与相对引用问题(比较杂乱,懒得整理)

    持续更新中,直到找到最好的方法

    1 在stackoverflows摘抄

    • If the import module in the same dir, use e.g: from . import core
    • If the import module in the top dir, use e.g: from .. import core
    • If the import module in the other subdir, use e.g: from ..other import core

    2 ValueError: Attempted relative import in non-package

    包含相对路径import 的python脚本不能直接运行,只能作为module被引用。原因正如手册中描述的,所谓相对路径其实就是相对于当前module的路径,但如果直接执行脚本,这个module的name就是“__main__”, 而不是module原来的name, 这样相对路径也就不是原来的相对路径了,导入就会失败,出现错误“ValueError: Attempted relative import in non-package”

    Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always"__main__", modules intended for use as the main module of a Python application should always use absolute imports.

    在使用相对引用的文件中,不能有__main__方法,只执行作为一个module进行引用,而不是直接执行脚本。

    3 利用路径引用其他目录下的文件

    首先图中的目录结构

    我在auth下的view.py文件上工作,但我需要app/aap.py中的变量db

    而我想用下面这个方式引入发现不成功

    方式一

    from ..app import db

    也查阅相关资料发现自己太愚并不能理解,所以另寻方法

     中间插一句

    sys.path.append('你的模块的名称')。

    sys.path.insert(0,'模块的名称')

    方式二

    import os
    import sys
    out = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(out)
    import app
    print app.db

    测试之后发现成功(yeh)其中这两个dirname就相当于返回到app/目录下,然后又在环境路径下添加了app/所以可以导入app.py,我偷懒直接导入需要的app.db

    方式三

    import sys
    sys.path.insert(0, '..')
    #此时路径已经在app文件下了
    import app
    print app.db

    4 命令行运行

    python -m 目录.文件名

    该方式是把模块当作脚本来启动(注意:但是__name__的值为'main' )

    相当于在sys.path中加入了当前路径

    5 把整个项目当做workspace

    目前为止最好的办法

     然后就可以进行绝对路径引用或者相对路径引用了。

  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
  • 原文地址:https://www.cnblogs.com/fuzzier/p/6116517.html
Copyright © 2011-2022 走看看