0

I'm a python newb, and am trying to build a Github python app in VSCode, link here: https://github.com/mapsme/osm_conflate

The devs aren't very responsive, and the problem is not very specific to the program, so I'm asking here. I made the launch.json file in the folder /home/janko/source/osm_conflate/.vscode/, the contents here:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${workspaceRoot}/conflate/conflate.py",
            "console": "integratedTerminal",
            "cwd": "${workspaceFolder}/conflate/",
            "args": [
                "-p", "/home/janko/Documents/profile.py",
                "-o", "josm.osm"
            ]
        }
    ]
}

And I get an error:

Exception has occurred: ImportError
attempted relative import with no known parent package
  File "/home/janko/source/osm_conflate/conflate/conflate.py", line 8, in <module>
    from .geocoder import Geocoder

I tried to change the python version from 3 to python2, but the text of the error just changes a bit. I tried to put other folders in the "cwd" property, but it's always the same. I tried to put other .py files in the "program" part of the json, but it doesn't help. What am I doing wrong?

Janjko
  • 71
  • 6
  • You may need a file called literally `__init__.py` to indicate that the directory may be used as a library https://stackoverflow.com/questions/448271/what-is-init-py-for – ti7 Jan 19 '21 at 17:11

1 Answers1

0

From PEP 328 -- Imports: Multi-Line and Absolute/Relative, we can know

Relative imports use a module’s name attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to main ) then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

To solve the encountered error, we may use absolute import instead of relative import.

  1. Change the folder conflate to other name, or else when you use from conflate.geocoder import Geocoder in conflate.py, it will throw a cirle import error.

  2. Copy the content in __init__.py then delete it. Paste the content to a new created __init__.py, then reload the window;

  3. Use pip install lxml to install the required module to the current environmet;

  4. In conflate.py, add sys.path.append('./') and import functions like from conflate.geocoder import Geocoder.

Finally you can run conflate.py successfully:

enter image description here

Molly Wang-MSFT
  • 7,943
  • 2
  • 9
  • 22