[英]Dumping the results into text file that has the same name as the variable
I'm trying to write a code using netmiko
that will execute few Show commands and save the results into text file with the name of variable (which is IP here). 我正在尝试使用netmiko
编写代码,该代码将执行一些Show命令并将结果保存到名称为变量(此处为IP)的文本文件中。
For example if I insert IP 8.8.8.8 I want the results to be save into a text file with the name 8.8.8.8. 例如,如果我插入IP 8.8.8.8,我希望将结果保存到名称为8.8.8.8的文本文件中。 Any ideas? 有任何想法吗?
The problem is that print
returns None
, and you're setting pre_r
equal to that print
call's return value: 问题是print
返回None
,并且您将pre_r
设置pre_r
等于该print
调用的返回值:
pre_r = print(connection.send_command(command))
Instead, set pre_r
equal to the data, and print
that instead: 相反,将pre_r
设置pre_r
等于数据,然后print
该数据:
for command in commands:
pre_r = connection.send_command(command)
print(pre_r)
with open(SwIp, 'wb') as f:
f.write(pre_r)
You also may want to move that for
loop inside the with
statement: 您可能还希望将for
循环移至with
语句内:
with open(SwIp, 'wb') as f:
f.writelines([connection.send_command(cmd) for cmd in commands])
Since the SwIp
variable appears to contain the IP address (as a string), you can do it by slightly changing how you open()
the file. 由于SwIp
变量似乎包含IP地址(作为字符串),因此可以通过稍微更改open()
文件的方式来实现。
with open(SwIp, 'wb') as f:
f.write(str(pre_r)+'\n')
Note I added a trailing newline to the data written to the file and removed the unnecessary f.close()
in your code (the with
will do that for you automatically). 注意,我在写入文件的数据中添加了尾随换行符,并删除了代码中不必要的f.close()
( with
将自动为您完成此操作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.