0

试图在语句中使用输入变量。

def email(account):
    email = fabric.operations.prompt("Enter client's email address:")
    run('mysql -u %s -p%s -e "UPDATE users SET email = %email WHERE id = 1" %s' % (env.user, dbpasswd, account))

错误:

  File "/tmp/fabfile.py", line 196, in email
    run('mysql -u %s -p%s -e "UPDATE users SET email = %email WHERE id = 1" %s' % (env.user, dbpasswd, account))
TypeError: float argument required, not str

任何想法!

4

2 回答 2

1

正如avasal所说, %email 是你的问题。即使你可以通过写 '%%' 来转义 '%' 字符,从 Python 2.6 开始,我鼓励你使用新的 format()语法,这样你就可以将它传递给 Python 3 而无需任何更改:

>>> template = 'mysql -u {} -p{} -e "UPDATE users SET email = %email WHERE id = 1" {}'
>>> query = template.format("user", "pass", "account")
>>> print(query)
mysql -u user -ppass -e "UPDATE users SET email = %email WHERE id = 1" account
>>> run(query)

此外,将模板与参数分开有助于避免代码重复,这是一种很好的做法,可以节省大量时间。

于 2012-07-30T12:48:55.117 回答
1

%email这应该是你的问题,

%e%email最后一个 %s 之前遇到字符串替换

In [4]: a = "1.2"

In [5]: print "%s" %a
1.2

In [6]: print "%e" %a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Python27\<ipython-input-6-1d66dedeb226> in <module>()
----> 1 print "%e" %a

TypeError: float argument required, not str

最简单的解决方法是:

cmd = 'mysql -u %s -p%s -e "UPDATE users SET email = ' %(env.user, dbpasswd) + '%email' + ' WHERE id = 1" %s' %account

run(cmd)

或者你也可以

data = "%email"
run('mysql -u %s -p%s -e "UPDATE users SET email = %s WHERE id = 1" %s' % (env.user, dbpasswd, data, account))
于 2012-07-30T08:53:44.673 回答