Python类型错误:没有足够的参数用于格式化字符串.看不出有什么不对



我的脚本中有这段python代码。

dataBase = str(request.forms.get('db')) 
data =  "/usr/local/Calpont/mysql/bin/mysql --defaults-file=/usr/local/Calpont/mysql/my.cnf  -u root %s -e "show tables like 'f_%s'"" %(dataBase)

但当我运行它时,它给了我以下错误:-

TypeError: not enough arguments for format string

有什么帮助吗?

您的格式字符串中有两个%s标记:

... -u root %s -e "show tables like 'f_%s' ...
            ^^                            ^^

但只有一个自变量database

对于标记的数量,您需要有足够的参数。最有可能的是,这只是以下其中一个简单的问题。

  • 如果您试图使用另一个参数,则需要提供它,例如... % (dataBase, tableName)
  • 如果您试图使用文字%标记,则需要将其转义为%%,而不是您可能认为的%

考虑到您使用的是like,我认为第二种可能性最大,因为%是该运算符的通配符。

以下转录本可能会使问题变得更清楚:

pax> python
Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "... -u root %s -e "show tables like 'f_%s' ..." %("A")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> print "... -u root %s -e "show tables like 'f_%s' ..." %("A","B")
... -u root A -e "show tables like 'f_B' ...
>>> print "... -u root %s -e "show tables like 'f_%%' ..." %("A")
... -u root A -e "show tables like 'f_%' ...
>>> _

第一个和第二个命令显示,使用两个%s标记需要两个参数。

第三个命令显示如何正确地转义字符串中的%

最新更新