脚本中的 python 语法错误,在 REPL 中正常

发布于 2024-12-23 05:23:39 字数 631 浏览 1 评论 0原文

当我将此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

删除→记忆 2024-12-30 05:23:39

这不起作用的原因是您没有任何信息告诉 bash 这是一个 Python 脚本,因此它尝试将其作为 shell 脚本执行,然后在语法不正确时抛出错误对。

您需要的是以 shebang 行开始文件,告诉它应该做什么一起运行。所以你的文件变成:

#!/usr/bin/env python

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

print get_header()

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:

#!/usr/bin/env python

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

print get_header()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文