使用关键字参数 end=' ' 打印时获取 SyntaxError [英] Getting SyntaxError for print with keyword argument end=' '

查看:58
本文介绍了使用关键字参数 end=' ' 打印时获取 SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 python 脚本,我需要在其中运行 gdal_retile.py,但我在这一行遇到了一个例外:

I have this python script where I need to run gdal_retile.py, but I get an exception on this line:

if Verbose:
   print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')

end=' ' 是无效语法.我很好奇为什么,以及作者可能打算做什么.

The end=' ' is invalid syntax. I am curious as to why, and what the author probably meant to do.

如果您还没有猜到,我是 Python 新手.

I'm new to python if you haven't already guessed.

我认为问题的根本原因是这些导入失败了因此必须包含这个 import from __future__ import print_function

I think the root cause of the problem is that these imports are failing and therefore one must contain this import from __future__ import print_function

try: 
   from osgeo import gdal
   from osgeo import ogr
   from osgeo import osr
   from osgeo.gdalconst import *
except:
   import gdal
   import ogr
   import osr
   from gdalconst import *

推荐答案

您确定您使用的是 Python 3.x 吗?该语法在 Python 2.x 中不可用,因为 print 仍然是一个语句.

Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.

print("foo" % bar, end=" ")

在 Python 2.x 中与

in Python 2.x is identical to

print ("foo" % bar, end=" ")

print "foo" % bar, end=" "

即作为以元组为参数的打印调用.

i.e. as a call to print with a tuple as argument.

这显然是错误的语法(文字不接受关键字参数).在 Python 3.x 中 print 是一个实际的函数,所以它也需要关键字参数.

That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.

Python 2.x 中 end=" " 的正确习惯用法是:

The correct idiom in Python 2.x for end=" " is:

print "foo" % bar,

(注意最后一个逗号,这使得它以空格而不是换行符结束行)

(note the final comma, this makes it end the line with a space rather than a linebreak)

如果您想对输出进行更多控制,请考虑直接使用 sys.stdout.这不会对输出产生任何特殊的影响.

If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.

当然,在 Python 2.x 的最新版本中(2.5 应该有,2.4 不确定),您可以使用 __future__ 模块在您的脚本文件中启用它:

Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:

from __future__ import print_function

unicode_literals 和其他一些不错的东西(例如,with_statement)也是如此.但是,这不适用于 Python 2.x 的真正旧版本(即在引入该功能之前创建).

The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.

这篇关于使用关键字参数 end=' ' 打印时获取 SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆