简体   繁体   English

脚本中的python语法错误,在REPL中很好

[英]python syntax error in script, fine in REPL

When I put this python code into the REPL for python (the interactive shell), it works as expected: 当我把这个python代码放入REPL for python(交互式shell)时,它按预期工作:

>>> def get_header():
...     return (None,None,None)
... 
>>> get_header()
(None, None, None)

Note that the return statement is indented by four spaces, and I have checked to ensure there are no extraneous spaces. 请注意,return语句缩进了四个空格,我已经检查以确保没有多余的空格。

when I put the exact same code into a python script file and execute it, I get the following error: 当我将完全相同的代码放入python脚本文件并执行它时,我收到以下错误:

./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def get_header():'

WHY? 为什么?

EDIT: this is the exact contents of test.py, white spaces and all: 编辑:这是test.py,空格和所有内容的确切内容:

def get_header():
    return (None,None,None)

get_header()

I have verified that the above script (test.py) does yield the above error as it above stands. 我已经验证上面的脚本(test.py)确实产生了上面的错误,如上所述。

The reason this is not working is that you don't have anything telling bash that this is a Python script, so it tries to execute it as a shell script, then throws an error when the syntax isn't right. 这不起作用的原因是你没有告诉bash这是一个Python脚本,所以它试图将它作为shell脚本执行,然后在语法不正确时抛出错误。

What you need is to start the file with a shebang line, telling it what it should be run with. 你需要的是用一个shebang行启动文件,告诉它应该运行什么。 So your file becomes: 所以你的文件变成:

#!/usr/bin/env python

def get_header():
    return (None, None, None)

print get_header()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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