繁体   English   中英

出于某种原因,我的函数返回“无”? 为什么?

[英]For some reason my function returns "None"? Why?

为什么 grepcut() 返回 None?

from termcolor import colored
from subprocess import *

def grepcut(inputRaw, grep, delimit, field):
    for line in inputRaw:
        if grep in line:
            output = line.split(delimit)[field]
            return output
        else:
            return None


def function():
    print(colored("[+] ", "green") + "Here we go!")
    inputRaw = Popen(["cat outputfile"], shell=True, stdout=PIPE, universal_newlines=True).communicate()[0].rstrip()
    var1 = grepcut(inputRaw, grep = 'grep this', field = 6, delimit = " ")
    var2 = grepcut(inputRaw, grep = 'grep this', field = 2, delimit = " ")
    print("\n")
    print(var1, var2)
    #if var1 or var2 is None:
    #   print(colored("[-] ", "red") + "Not found!!!")
    #else:
    #   print(var1, var2)

function()

顺便说一下,这是 inputRaw 的内容:

ABCDEFG
HIJ grep 这个 KLMN
OPQRSTU

这段代码的输出是:
无 无

您的grepcut仅检查第一行:如果匹配,则返回output ,否则立即返回None ,而不进行下一次迭代。

可能您想删除该else分支并在for之后移动return None

def grepcut(inputRaw, grep, delimit, field):
    for line in inputRaw:
        if grep in line:
            output = line.split(delimit)[field]
            return output
    return None

你甚至可以省略return None ,如Python中的任何功能终止没有明确的return不回报None ,但我会保留它,要清楚,这不是疏忽,但功能有望恢复None如果它不找不到任何东西。


此外,您正在通过Popen调用communicate() ,因此您将返回一个string ,而不是一个文件对象; 因此,您不能像那样直接在其行上进行迭代 - 对字符串进行迭代会对其字符进行迭代。

如果inputRaw确实是一个字符串,则必须拆分换行符,如下所示:

def grepcut(inputRaw, grep, delimit, field):
    for line in inputRaw.split('\n'):
        if grep in line:
            output = line.split(delimit)[field]
            return output
    return None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM