脚本的绝对和相对导入
Absolute and relative importing for scripts
我知道这个问题经常被问到,但我有一个关于导入的非常具体的问题。我的文件结构如下:
main/main.py
main/test_device.py
main/lib/instructions.py
main/device/android.py
main/temp/example.py
基本上,这里发生的事情是我的程序 (main.py
) 创建几个较小的脚本(在 temp/
中),然后尝试 运行 它们。但是,这些脚本中的每一个都引用了 lib/instructions.py
和 device/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
个文件,但是因为这些文件是脚本,所以我不能使用相对导入。我将如何导入这些库?
将您的模块复制到 python/lib/site-packages 可以解决问题。
如果我理解你的话,你需要你在内容中构建的脚本才能从你的包中导入其他模块,但它不能要求正确的目标目录 b/c它本身就是一种尴尬的相对进口。在加入列表之前尝试添加此行
contents.insert(0, "import sys; sys.path.append('lib'); sys.path.append('device')")
这里已经很晚了,我正在 phone 所以可能有错字,但我希望这对你有用。
编辑:根据当前工作目录,您可能需要附加“../lib”或使用绝对路径
我知道这个问题经常被问到,但我有一个关于导入的非常具体的问题。我的文件结构如下:
main/main.py
main/test_device.py
main/lib/instructions.py
main/device/android.py
main/temp/example.py
基本上,这里发生的事情是我的程序 (main.py
) 创建几个较小的脚本(在 temp/
中),然后尝试 运行 它们。但是,这些脚本中的每一个都引用了 lib/instructions.py
和 device/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
个文件,但是因为这些文件是脚本,所以我不能使用相对导入。我将如何导入这些库?
将您的模块复制到 python/lib/site-packages 可以解决问题。
如果我理解你的话,你需要你在内容中构建的脚本才能从你的包中导入其他模块,但它不能要求正确的目标目录 b/c它本身就是一种尴尬的相对进口。在加入列表之前尝试添加此行
contents.insert(0, "import sys; sys.path.append('lib'); sys.path.append('device')")
这里已经很晚了,我正在 phone 所以可能有错字,但我希望这对你有用。
编辑:根据当前工作目录,您可能需要附加“../lib”或使用绝对路径