Pythonic方式返回布尔值和消息

这个问题在这里已经有了答案:

  • 你如何在Python中返回多个值? 13个答案

  • Python中的空字符串“falsey”,所以返回有点多余(False,'')。 我可能会这样做:

    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)
    

    (见4.1真值测试)


    我认为这也会是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/53125.html

    上一篇: Pythonic way to return a boolean value and a message

    下一篇: Twitter Authentication through Android's AccountManager classes