如何在Windows上使用Python导入本地包?

时间:2017-11-17 09:15:16

标签: python anaconda pythonpath mako

我想从包 mako 中使用mako-render

考虑以下3个文件:

d:\ test.py
from module import foo
print(foo())
d:\ test.txt的
<%! from module import foo %>
${foo()}
d:\测试\ module.py
def foo():
    return 42

如果我想执行foo.py,我需要将D:\test添加到PYTHONPATH

d:\>C:\ProgramData\Anaconda3\python.exe test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from module import foo
ModuleNotFoundError: No module named 'module'

d:\>set PYTHONPATH=D:\test;%PYTHONPATH%

d:\>C:\ProgramData\Anaconda3\python.exe test.py
42

mako-render的情况有所不同。在POSIX系统上mako-render只是一个在底层调用Python的脚本。在Windows上,它是可执行文件mako-render.exe。所以,如果我这样做,它不起作用:

d:\>C:\ProgramData\Anaconda3\Scripts\mako-render.exe test.txt

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\Mako-1.0.7-py3.6.egg\mako\cmd.py", line 55, in cmdline
    template = Template(filename=filename, lookup=lookup)
  File "C:\ProgramData\Anaconda3\lib\site-packages\Mako-1.0.7-py3.6.egg\mako\template.py", line 338, in __init__
    module = self._compile_from_file(path, filename)
  File "C:\ProgramData\Anaconda3\lib\site-packages\Mako-1.0.7-py3.6.egg\mako\template.py", line 416, in _compile_from_file
    filename)
  File "C:\ProgramData\Anaconda3\lib\site-packages\Mako-1.0.7-py3.6.egg\mako\template.py", line 714, in _compile_text
    exec(code, module.__dict__, module.__dict__)
  File "test_txt", line 16, in <module>

ImportError: cannot import name 'foo'

它在Windows上如何运作?

如果我从Linux mako-render复制到D:\my-mako-render,我可以这样做:

d:\>C:\ProgramData\Anaconda3\python.exe -m my-mako-render test.txt
42

42

因此问题出现在.exe个文件中。

0 个答案:

没有答案