命令行python没有输出

时间:2013-10-12 23:45:30

标签: python command-line

这是我的代码。当我运行它时,它只是在运行后退出。没有印刷品。为什么这样 ?

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break

if callfunc == 'initialize':
    print listdir() #this will print list of files
    print "\n"

for files in listdir():
    checkString(files,"hello")

if found:
    print "String found"
else:
    print "String not found"
input.close()

2 个答案:

答案 0 :(得分:0)

found是函数checkString()中的本地名称;它保持在本地,因为你不归还它。

从函数返回变量并存储返回值:

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break
    return found

for files in listdir():
    found = checkString(files,"hello")
    if found:
        print "String found"
    else:
        print "String not found"

答案 1 :(得分:0)

您需要修改为:

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break

    input.close()
    return found

found = False

if callfunc == 'initialize':
    print listdir() #this will print list of files
    print "\n"

for files in listdir():
    found = found or checkString(files,"hello")

if found:
    print "String found"
else:
    print "String not found"

这是因为您的原始found仅在函数checkString

范围内