Can you import a Python module from a Windows symb

2019-08-06 19:14发布

问题:

I'm contributing to a Python 3 project from a Windows 7 computer.

In order to minimise clutter while making and testing changes, I'm placing a few test files inside a folder called ignore within the project, and excluding it from the version control system (Git).

There is no __init__.py file in the root of the project, so I thought I'd create a symbolic link from the module I want to test into the ignore folder, to enable me to import it.

mklink ignore\example.py example.py

When I try to import the module from a script in ignore I get an ImportError saying the example module doesn't exist.

Is it possible to import modules via symbolic links in this way? I understand that this is supposed to work, but I can't find a reference saying that it works on Windows.

回答1:

I have just spent +2 hours trying to resolve this issue and it turned out that creating a Windows Directory Junction worked for me.

You don't need to use a relative one, it worked with both.

So first create an empty file __init__.py in your igonore-folder then in the elevated mode (As Administrator) create a link:

mklink /J ignore path-to-your-ignore-module

Then in your Python code you would be able to execute: from ignore.something import some-other-thing