如何阻止当前功能中的先前功能进行打印?

时间:2019-02-18 05:40:42

标签: python

我目前正在为类编写一个测试函数,以在提供的解决方案代码上测试提供的案例。但是,我遇到了一个我不希望执行打印语句的问题。

这是我正在测试的提供的解决方案:

def alphapinDecode(tone):
     phone_num = ''

if checkTone(tone):         #or checkTone2
    while len(tone) > 0:

        # retrieve the first tone
        next_tone = tone[0:2]
        tone = tone[2:]

        # find its position
        cons = next_tone[0]
        vow = next_tone[1]

        num1 = consonants.find(cons)
        num2 = vowels.find(vow)

        # reconstruct this part of the number -
        # multiply (was divided) and add back
        # the remainder from the encryption division.
        phone = (num1 * 5) + num2

        # recreate the number
        # by treating it as a string
        phone = str(phone)

        # if single digit, not leading digit, add 0
        if len(phone) == 1 and phone_num != '':
            phone = '0' + phone

        phone_num = phone_num + phone

    # but return in original format
    phone_num = int(phone_num)

else:
    print('Tone is not in correct format.')
    phone_num = -1
return phone_num

这是我编写的测试函数的(部分完成)代码:

def test_decode(f):
    testCases = (
            ('lo', 43),
            ('hi', 27),
            ('bomelela', 3464140),
            ('bomeluco', 3464408),
            ('', -1),
            ('abcd', -1),
            ('diju', 1234),
            )

    for i in range(len(testCases)):
        if f(testCases[i][0]) == testCases[i][1] and testCases[i][1] == -1:
            print('Checking '+ f.__name__ + '(' + testCases[i][0] + ')...Tone is not in correct format.')
            print('Its value -1 is correct!')
    return None

执行test_decode(alphapinDecode)时,我得到了:

Tone is not in correct format.
Checking alphapinDecode()...Tone is not in correct format.
Its value -1 is correct!
Tone is not in correct format.
Checking alphapinDecode(abcd)...Tone is not in correct format.
Its value -1 is correct!

如您所见,由于alphapinDecode(我认为)中的print语句,它正在打印额外的“ Tone格式不正确”。在我写的打印声明上方。

我将如何阻止执行该打印语句,并且如果我在测试函数中编写的打印语句不要求输入alphapinDecode的结果,为什么还要打印该打印语句?

我们不允许更改给定解决方案的代码。

我对stackOverflow还是很陌生,所以对任何格式化问题都感到抱歉。谢谢!

编辑:修复了test_decode函数的标识

1 个答案:

答案 0 :(得分:0)

一个简单的解决方案是将一个额外的参数(即布尔变量debug)传递给该函数。那会是这样的。

def func1(var1, debug):
    if debug:
        print("Printing from func1")
    # Do additional stuff

现在,当您调用它时。现在,您可以选择设置调试变量。

func1("hello", debug=True) # will print the statement
func1("hello", debug=False) # will not print statement.

如果无法修改调用的函数。然后,您可以按照此方法。由@FakeRainBrigand here解释。

import sys, os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__


print 'This will print'

blockPrint()
print "This won't"

enablePrint()
print "This will too"