简体   繁体   中英

python configparser hangs silently

I have a feeling I'm being stupid. Given this ini file:

[main]
source1 = ./testing/sdir1
sync1 = ./testing/sydir1
archive1 = ./testing/adir1
source2 = ./testing/sdir2
sync2 = ./testing/sydir2
archive2 = ./testing/adir2
[logging]
log_dir = .
log_file = pixelsync.log
log_level = DEBUG

The following code hangs:

import ConfigParser

CONFIG_FILE = 'pixelsync.ini'

def parse_config() :
    """read details from the config file"""
    global CONFIG_FILE
    config = ConfigParser.SafeConfigParser()
    config.read(CONFIG_FILE)
    index = 1
    while True :
        if config.has_option('main', 'source' + str(index)) and \
                    config.has_option('main', 'sync' + str(index)) and \
                    config.has_option('main', 'archive' + str(index)) :

            result = ( config.get('main', 'source' + str(index)),
                       config.get('main', 'sync' + str(index)),
                       config.get('main', 'archive' + str(index)))
            index += 1
        else :
            if index == 1 :
                print "could not setup any trios from the config file. exiting."
                sys.exit(1)
    return result

if __name__ == '__main__' :
    options = parse_config()

It hangs on the 'if' clause.

If I replace the 'if' clause with :

if config.has_option('main', 'source1' ) and \
                    config.has_option('main', 'sync1' ) and \
                    config.has_option('main', 'archive1' ) :

it doesn't hang. (doesn't do what I want since I need to loop through an arbitrary number of sets of three, but it doesn't silently hang.

Python v2.7.3 on ubuntu 12.04 (Precise), 32bit.

The reason your program hangs is it never breaks out of the loop - it goes on forever. Rather than simply setting result , you need to return it. (An alternative is to set it and then use break to break out of the loop and return, but that is somewhat roundabout. It's better to simply return it straight away.

Note that doing while True: and counting like that isn't very Pythonic, the preferred approach is to instead use itertools.count() .

Eg:

import itertools

...

for index in itertools.count(1):
    ...

Note that this shows a design flaw. You probably want to have a way of knowing if you are never going to get a suitable result. Infinite loops are generally bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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