脚本中的 python 语法错误,在 REPL 中正常
当我将此 python 代码放入 python(交互式 shell)的 REPL 中时,它按预期工作:
>>> def get_header():
... return (None,None,None)
...
>>> get_header()
(None, None, None)
请注意,return 语句缩进了四个空格,并且我已检查以确保没有多余的空格。
当我将完全相同相同的代码放入Python脚本文件并执行它时,我收到以下错误:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def get_header():'
为什么?
编辑:这是准确 test.py 的内容、空格和所有内容:
def get_header():
return (None,None,None)
get_header()
我已经验证上述脚本(test.py)确实会产生上述错误。
When I put this python code into the REPL for python (the interactive shell), it works as expected:
>>> 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.
when I put the exact same code into a python script file and execute it, I get the following error:
./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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不起作用的原因是您没有任何信息告诉
bash
这是一个 Python 脚本,因此它尝试将其作为 shell 脚本执行,然后在语法不正确时抛出错误对。您需要的是以 shebang 行开始文件,告诉它应该做什么一起运行。所以你的文件变成:
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.What you need is to start the file with a shebang line, telling it what it should be run with. So your file becomes: