简体   繁体   中英

Shebang line for python does not work at all

It is a tough problem. There are several topics for it. But none of them helps me.

I added #!/usr/bin/env python3 (or python), and run test.py , it reported that zsh: command not found: test.py . I was confused. I had tried many forms of shebang. Can you help me?

In following error reports, you can see that the reports are different when running it under HOME path and under the parent path of test.py

[Scripts] test.py                                                     20:51:04
zsh: command not found: test.py
[Scripts] cd ~                                                        20:51:33
[~] Scripts/test.py                                                   20:51:43
env: python\r: No such file or directory

It's not so long since I got the meaning of the shebang line. I hope that it can make my life easy, never writing python before test.py .

Following is the test code.

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser(description='test')
parser.add_argument('-o', dest='what', action='store', default='hello', metavar='WHAT')

args = parser.parse_args()
print(args.what)

Following is the configuration.

PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:$PATH"

And in terminal,

[~] which python                                                      20:36:55
python: aliased to python3
[~] which python3                                                     20:36:57
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
ls -l
-rwxrwxrwx@ 1 william  staff   273 10 24 20:51 test.py

Assuming that the directory of test.py is not in your PATH , you will need to use either a relative or absolute path, and ensure that the script has execution privileges.

$ chmod u+x test.py
$ ./test.py

Should execute properly.


With the error env: python3\\r: No such file or directory : the file is using "CRLF" newlines: \\r\\n , while a single \\n is expected. So zsh is splitting on the first \\n , leaving the shebang line #!/usr/bin/env python3\\r , with python3\\r obviously not in your PATH . If you change the line endings with unix2dos test.py , that should fix the issue as per this answer .

After adding the shebang to your python file:

  • Make the file executable chmod +x test.py
  • Run the file while in the directory it exists ./test.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM