【问题标题】:Absolute and relative importing for scripts脚本的绝对和相对导入
【发布时间】:2016-07-19 13:39:05
【问题描述】:

我知道这个问题经常被问到,但我有一个关于导入的非常具体的问题。我的文件结构如下:

main/main.py
main/test_device.py
main/lib/instructions.py
main/device/android.py
main/temp/example.py

基本上,这里发生的情况是我的程序 (main.py) 创建了几个较小的脚本(在 temp/ 中),然后尝试运行它们。但是,这些脚本中的每一个都引用了lib/instructions.pydevice/android.py。此代码运行这些文件:

name = "temp/test_" + str(program_name) + ".py"
input_file = open("test_device.py", "r")
contents = input_file.readlines()
input_file.close()
contents.insert(7, "program = [" + ", ".join(str(i) for i in instructions) + "]\r\n")
contents.insert(8, "count = " + str(program_name) + "\r\n")
contents = "".join(contents)
input_file = open(name, "w+")
input_file.write(contents)
Popen("python " + name)

我在每个目录中都有__init__.py 文件,但是因为这些文件是脚本,所以我不能使用相对导入。我将如何导入这些库?

【问题讨论】:

  • 向我们展示您用于在temp 目录中运行脚本的代码。
  • @Sevanteri 我已经上传了代码

标签: python import relative-import


【解决方案1】:

如果我理解你的话,你需要你在内容中构建的脚本才能从你的包中导入其他模块,但它不能要求正确的目标目录 b/c 它的一种尴尬的相对导入高于自身。在加入列表之前尝试添加此行

contents.insert(0, "import sys; sys.path.append('lib'); sys.path.append('device')")

这里已经很晚了,我正在打电话,所以可能有错字,但我希望这对你有用。

编辑:根据当前的工作目录,您可能需要附加“../lib”或使用绝对路径

【讨论】:

  • 我不是特别喜欢以这种方式使用sys,但我想这无济于事。感谢您的解决方案。
  • 不客气。是的,我猜它的命名方式几乎听起来像是您要进行系统范围的设置更改,但实际上更改只会影响您执行它的命名空间并且它不是持久的
【解决方案2】:

将你的模块复制到 python/lib/site-packages 可以解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2019-06-28
    • 2019-05-14
    • 1970-01-01
    • 2020-08-31
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多