Linux/Unix executes the ./xxx.py file in the background and reports an error syntax error near unexpected token 'xxxxxx'

#!/usr/bin/python in python script


It is estimated that many people have noticed that some python scripts start with something like this:
#!/usr/bin/python
What is it used for? It doesn't seem to have any effect on script functionality without it. It is used to specify what interpreter is used to run the script and where the interpreter is located.

Taking hello.py as an example, the content of the script is as follows:

def test():
        print 'hello, world'

if __name__ == "__main__":
        test()

Run the script:
python3  hello .py
output:
hello, world

Run another way :
./ hello .py
will prompt an error, the file has no executable permission:
-bash: ./ hello .py: Permission denied

Make the file executable:
chmod +x hello .py
continue to run:
./ hello .py
prompt:
./ hello .py: line 1: syntax error near unexpected token `('
./hello .py: line 1: `def test():'
That's because the system defaults that the script is a shell script, execute it as a shell statement, of course it fails. Add #!/usr/bin/python3

in front of it to declare: this is a python3 script, to be run with a python interpreter: ./hello .py output: hello, world This stuff is commonly used in cgi scripts, Apache (Apa Odd: WEB server software) depends on it to know that this is a python script and the path of the python interpreter needed to execute it when it starts the cgi script. Sometimes writing #!/usr/bin/python3 still doesn't work, it's very simple, because the python interpreter is not installed in the /usr/bin/ directory, just change it to the directory where it is located, or a more general method is: #!/usr /bin/env python3








Or: if you run the shell script written in windows and run it in the linux system, you will be prompted with the following error syntax error near unexpected token `... This is because the line breaks under the two platforms are different. So you need to convert the format, notepad++ has this function.

1. First open notepad++, let the script display all symbols, and find that it is CR LF

View -> Show Symbols -> Show All Symbols

2. We need to convert the windows format to linux format, and do the following operations.

Edit -> File Format Conversion -> Convert to UNIX Format

3. After the conversion, it is found that the carriage return line feed has changed. Then put it into linux and there will be no error.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325650852&siteId=291194637