为什么我的 Python 脚本会因语法错误而失败?

Nai*_*ive 4 python command-line

在运行下面的简单 Python 程序时,出现以下错误:

./url_test.py: line 2: syntax error near unexpected token `('                  
./url_test.py: line 2: `response = urllib2.urlopen('http://python.org/')'
Run Code Online (Sandbox Code Playgroud)
import urllib2      
response = urllib2.urlopen('http://python.org/')  
print "Response:", response

# Get the URL. This gets the real URL. 
print "The URL is: ", response.geturl()

# Getting the code
print "This gets the code: ", response.code

# Get the Headers. 
# This returns a dictionary-like object that describes the page fetched, 
# particularly the headers sent by the server
print "The Headers are: ", response.info()

# Get the date part of the header
print "The Date is: ", response.info()['date']

# Get the server part of the header
print "The Server is: ", response.info()['server']

# Get all data
html = response.read()
print "Get all data: ", html

# Get only the length
print "Get the length :", len(html)

# Showing that the file object is iterable
for line in response:
 print line.rstrip()

# Note that the rstrip strips the trailing newlines and carriage returns before
# printing the output.
Run Code Online (Sandbox Code Playgroud)

And*_*ini 8

这些错误不是典型的 Python 回溯。这些错误看起来像 shell 错误。

我认为您正在尝试使用 Bash(或另一个 shell)运行 Python 脚本,即您正在执行以下操作:

bash url_test.py
Run Code Online (Sandbox Code Playgroud)

相反,您应该使用:

python url_test.py
Run Code Online (Sandbox Code Playgroud)


Rad*_*anu 8

您错过了在脚本开头添加一个shebang来告诉 shell 将您的脚本解释为 python 脚本。像这样的东西:

#!/usr/bin/python
Run Code Online (Sandbox Code Playgroud)

或者:

#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)

另请参阅:为什么人们在 Python 脚本的第一行写 #!/usr/bin/env python?