几乎相同的打印命令无法编译

2024-04-26 03:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的python脚本,用于从mysql数据库检索信息。 下面是两个几乎相同的示例,第一个示例成功编译,而第二个示例返回:

      File "dbconnection.py", line 17
    print ip
           ^
SyntaxError: invalid syntax

我尝试从第二个示例中删除try-catch代码,但没有结果。 有一个相关的poston syntax error on Python 3使我的第二个示例成功运行,但它没有回答“为什么这些几乎相同的示例有不同的行为”的问题。你知道吗

第一个例子:

import datetime
import mysql.connector

cnx = mysql.connector.connect(user='user', database='test', password='test')
cursor = cnx.cursor()

query = ("SELECT ip FROM guralps")
cursor.execute(query)

for (ip) in cursor:
  print ip

cursor.close()
cnx.close()

第二个不编译:

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
from mysql.connector import errorcode
import time


try:

  cnx = mysql.connector.connect(user='user', database='test', password='test')
  cursor = cnx.cursor()

  query = ("SELECT ip FROM guralps")
  cursor.execute(query)

  for (ip) in cursor:
    print ip

  cursor.close()
  cnx.close()

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exists")
  else:
    print(err)
else:
  cnx.close()

Tags: testimportip示例closeconnectordatetimemysql
2条回答

未来导入print\u函数,除法需要Python2.6或更高版本。打印功能允许您使用打印功能。因此不能将其用作打印ip。你知道吗

>>> from __future__ import print_function
>>>print('# of entries', len(dictionary), file=sys.stderr)

您使用了:

from __future__ import print_function

在模块顶部。此禁用该模块的print语句,以便您可以使用^{} function

print(id)

从函数文档:

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

from __future__ import print_function

相关问题 更多 >

    热门问题