Shebang doesn't work with python3

后端 未结 4 1716
执笔经年
执笔经年 2020-12-25 10:54

I have the following program:

#!/usr/local/bin/python3

print(\"Hello\")

Via terminal I do test.py and I get:

         


        
相关标签:
4条回答
  • 2020-12-25 11:12

    Another reason can be the presence of the byte order mark (BOM) at the start of the file, if the file is using an Unicode encoding.

    The presence of the BOM was my problem for my Python script encoded in UTF-8. I removed the BOM using my text editor Geany, but Notepad++ can also remove it, and I was able to run my script with a starting shebang line with ./myscript.py .

    To quote Wikipedia :

    The Unicode Standard permits the BOM in UTF-8, but does not require or recommend its use. Byte order has no meaning in UTF-8 [...]

    0 讨论(0)
  • 2020-12-25 11:21

    You might see ImportError: No module named '_sysconfigdata_m' because /usr/lib/command-not-found is broken on your system due to the ubuntu bug.

    To workaround it, run ./test.py, not test.py -- the current directory is not in $PATH usually (due to security reasons) and therefore you should specify the path explicitly otherwise the command is not found that may lead to trying to run /usr/lib/command-not-found that results in the ImportError.

    If ./test.py fails with the same error then check that there is no '\r\v\f' (unexpected whitespace) in the shebang (print(repr(open('test.py', 'rb').readline()))). If test.py uses Windows newlines then the attempt to find '/usr/local/bin/python3\r' (notice: '\r' due to '\r\n' newline) is likely to fail that may trigger the error.

    0 讨论(0)
  • 2020-12-25 11:31

    Windows end line was my problem too. Writing the same program with a linux editor like VI solved it for me. Also, using "less" command , i was able to see the windows end line characters

    0 讨论(0)
  • 2020-12-25 11:35

    Generally, take care of some pitfalls:

    1. set the executable flag on the script: chmod u+x test.py

    2. try to execute with a preceding dot "./", so call ./test.py otherwise it might execute some other script from within your PATH

    3. also make sure you don't have windows line endings, this seems to prevent the shebang evaluation, too. There are some suggestions around, e.g. in this answer, on how to convert the format.

      If python3 test.py works, then the windows line endings are probably your problem.

    4. #!/usr/bin/env python3 is the best way to define the shebang (i.e. use this as first line of your script), since the python binary may be installed somewhere else. env will inspect the PATH environment to find the binary

    5. As @ShaileshKumarMPatel has pointed out in the comments here, make sure, there's no wrong line beginnings (color characters etc)

    EDIT: The OP's kind of error looks like windows line endings to me. I've had them, too, with different output though

    0 讨论(0)
提交回复
热议问题