Search code examples
pythonpython-3.xwindows-subsystem-for-linuxshebang

shebang not working on WSL (Windows Subsystem Linux)


I installed WSL (Ubuntu 18.04) on Windows 10 to use instead of using parallel 2 OS. However, when I was using shebang, I couldn't run the script named test_file.py successfully. First, I created a folder named test_project. In this folder, I created:

  • An src folder that contains a simple Python script is shown as follows
    #!/usr/bin/env python3                 
    print("Hello world")
    
  • A Python environment folder named environment through python3 -m venv environment/ (I'm using Python 3.6)

The problem is when I stepped into the environment and typed some commands like in the attached picture Run python file, the program ran "command not found" although I already used shebang at the beginning of the code.

Apart from that, I also changed #!/usr/bin/env to #!/usr/bin/python3 and escape the environment, it didn't work as well. Only when I type Python3 test_file.py it worked.

Has anyone faced this problem before? Can anyone explain to me why this happens? I'm wondering whether it is different between using WSL compared to Ubuntu in this case, or I was missing some steps during coding. I know that this problem is debated common previously, however I couldn't find any source that can tackle my problem. I really appreciate all your help.


Solution

  • I had the same issue and resolved it by the changing the line endings from CRLF which is native to Windows to LF which is what the shell is expecting.

    You can do this with the dos2unix command:

    dos2unix -b test_file.py
    

    You'll probably need to install dos2unix on some newer distributions.

    There are other methods that can be used as well.