python-3.xvisual-studio-codepython-3.6windows-subsystem-for-linux

How to get Visual Studio Code working with python installed on WSL


I installed python3.6 on wsl and set my VSC integrated terminal to bash in the settings.json

If I set python.pythonPath: "python3" the VSC then warn me to select python environment and shows only the python installations on Windows. Is there a way I can add the python3 I installed on wsl to the python environment list in VSC or get rid of the warning?

Also, when I try to Run Python File in Terminal, it uses absolute path python3 c:/Users/xxx/Code/test.py which can't open the file in bash since there's no such file or directory. What do I need to change in the VSC settings so it will use python3 /mnt/c/Users/xxx/Code/test.py?

Similar issue reported on github regarding path translation in VSC.

Or is it better if I just run the python file from bash manually to avoid all the incompatibility issue with VSC and WSL?


Solution

  • I was able to find a work around from similar issues submitted on Microsoft's vscode and WSL Github repository about php.

    To Run Python File in Terminal in VSC, you will need to switch back to cmd as your integrated terminal in the settings.json

    Create a batch file python3.bat as follow:

    @echo off
    set v_params=%*
    set v_params=%v_params:\=/%
    set v_params=%v_params:c:=/mnt/c%
    set v_params=%v_params:"=\"%
    bash.exe -c "python3 %v_params%"
    

    Change set v_params=%v_params:c:=/mnt/c% accordingly based on your home. (ex. If you are running python file located in D: change this line to set v_params=%v_params:d:=/mnt/d%

    In settings.json add/change as follow:

    "python.pythonPath": "C:\\path\\to\\bat\\python3"

    To test your settings, create a test.py file as follow:

    import sys
    
    print(sys.executable)
    

    and right click in VSC to Run Python File in Terminal, the output should be /usr/bin/python3

    Note: although the bat script worked but in VSC it will still warn you to Select Python Environment