Pythonic way to return a boolean value and a message

This question already has an answer here:

  • How do you return multiple values in Python? 13 answers

  • An empty string in Python is "falsey", so it's somewhat redundant to return (False, ''). I might do this instead:

    def processGroupFound():
        if _isProcessRunning('ps auwxx | grep duplicity'):
            return 'Duplicity'
        elif _isProcessRunning('who | grep pts'):
            return 'SSH'
        elif _isProcessRunning('netstat -na | grep ESTA | grep 5901'):
            return 'VNC'
        else:
            return ''
    
    def worker():
        while True:
            service_string = processGroupFound()
            if service_string:
                print('{} found; skipping'.format(service_string))
            else:
                print('Continuing on')
            time.sleep(10)
    

    (See 4.1 Truth Value Testing)


    我认为这也会是pythonic(但可能只是我)

    class NoRunningService(RuntimeError): pass
    
    def findService():
        if _isProcessRunning('ps auwxx | grep duplicity'):
            return 'Duplicity'
        elif _isProcessRunning('who | grep pts'):
            return 'SSH'
        elif _isProcessRunning('netstat -na | grep ESTA | grep 5901'):
            return 'VNC'
        else:
            raise NoRunningService
    
    def worker():
        while True:
            try:
                service_string = findService()
            except NoRunningService:
                print('Continuing on')
            else:
                print('{} found; skipping'.format(service_string))
            time.sleep(10)
    
    链接地址: http://www.djcxy.com/p/53126.html

    上一篇: 如何在Python中传入和传出函数中的变量

    下一篇: Pythonic方式返回布尔值和消息