【问题标题】:Printing a output (a function?) to a file?将输出(函数?)打印到文件?
【发布时间】:2014-08-06 11:28:02
【问题描述】:

我有一个 Python 脚本,我在其中登录 Cisco 设备并希望将命令的输出打印到文件中。

我的输出一切正常,但不确定如何将其打印到文件中。

这是我的登录代码,打印我需要的输出,然后注销。效果很好——我知道它不优雅:)

import pexpect

HOST = "172.17.1.1"
user = "username"
password = "password"

policymap = pexpect.spawn ('telnet '+HOST)
policymap.expect ('Username: ')
policymap.sendline (user)
policymap.expect ('Password: ')
policymap.sendline (password)
routerHostname = "switch1"
policymap.expect (routerHostname+'#')
policymap.sendline ('sh policy-map interface gi0/1\r')
print(policymap.readline())
policymap.expect (routerHostname+'#')
policymap.sendline ('exit\r')
print policymap.before

我尝试添加一个函数并将函数的输出打印到文件中,但我想我可能走错了路?

def cisco_output():
        print policymap.before

filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output)
target.close()

【问题讨论】:

  • 您使用的是哪个 Python 版本?您同时使用了printprint(),这很不寻常。
  • 您应该使用with 打开您的文件。

标签: python function output


【解决方案1】:

不要在函数内部使用print,而是return 要保存的内容。然后通过将() 附加到函数名称来调用该函数。

def cisco_output():
    return policymap.before

filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output())
target.close()

【讨论】:

    【解决方案2】:
    with open("policymap.txt", "w") as f:
        print >>f, policymap.before
    

    【讨论】:

    • with 很好,但问题是关于打印 function 的结果,而不是对象属性。