关于citizenshell.SecureShell()方法返回值类型转换
背景
使用citizenshell.SecureShell()
连接远程的一台Linux机器,然后在shell里去读一个文件并且统计该文档中某个关键字出现的次数。后面需要使用这个次数进行算数运算。
def Count_words(count_word):
shell = citizenshell.SecureShell(hostname=ip, username='xxxxx', password='xxxxx')
out = shell("grep '%s' %s | wc -l"%(count_word,logfile))
return out
num=Count_words(count_word1)-Count_words(count_word2)
运行以上代码报错如下:TypeError: unsupported operand type(s) for -: 'ShellResult' and 'ShellResult'
,然后尝试把shell返回值转int
,修改如下代码:
def Count_words(count_word):
shell = citizenshell.SecureShell(hostname=ip, username='xxxxx', password='xxxxx')
out = shell("grep '%s' %s | wc -l"%(count_word,logfile))
out = int(out)
return out
运行以上代码报错如下:AttributeError: ShellResult instance has no attribute '__trunc__'
查了一下shell返回值的类型<class 'citizenshell.shellresult.ShellResult'>
,看着是个特殊的类型,反正不能转int
。
之前只用过str
转int
,遇到这种情况毫无头绪啊~~
灵光一闪,是不是可以将shell返回值先转str再转int呢~ 尝试一下~
def Count_words(count_word):
shell = citizenshell.SecureShell(hostname=ip, username='xxxxx', password='xxxxx')
out = shell("grep '%s' %s | wc -l"%(count_word,logfile))
out = int(str(out))
return out
num=Count_words(count_word1)-Count_words(count_word2)
完美解决~