将变量传递给命令 - 格式字符串的参数不足

Passing a variable to a command - not enough arguments for format string

您好,我有以下测试代码块(测试实验室)。

#<snip>
client_mac = 'f8:cf:c5:a4:a2:84'
#<snip>
# issue a command1
my_command_output1 = my_wlc_session.sendcommand("grep include f8:cf:c5:a4:a2:84 \"show client summary\" \n")
# print the output
print(my_command_output1)
#
# issue a command2
my_command_output2 = my_wlc_session.sendcommand("grep include %s \"show client summary\" \n") % client_mac
# print the output
print(my_command_output2)
#<snip>

Command1 按预期工作。

但 command2 是问题所在。我想要某种方式将 client_mac 传递给命令,但是我使用的代码导致了这个;

TypeError: not enough arguments for format string

我认为这与 /n 有关,但我需要在命令后添加第二个换行符才能执行它。

有没有更好的方法来传递client_mac?还是我做错了什么。

您的右括号似乎碍事了。尝试:

my_command_output2 = my_wlc_session.sendcommand("grep include %s \"show client summary\" \n" % client_mac)

当您使用它时,新的 .format() 正变得越来越流行,并使此类错误更容易被发现。看起来像:

my_command_output2 = my_wlc_session.sendcommand("grep include {} \"show client summary\" \n".format(client_mac))

你的代码问题在这里:

("grep include %s \"show client summary\" \n") % client_mac

您的 % client_mac 应该在括号内,您要将其格式化为 ("grep include %s \"show client summary\" \n")。

该错误意味着您指定了格式字符串 (%s) 但未包括要插入的变量(因为它在括号之外,因此不是表达式的一部分)。

Re-reading 你的问题,我相信你困惑的根源是你认为你正在将多个参数传递给你的函数。您实际上只是传递了一个参数,一个字符串(您正在格式化以包含 client_mac)。