2012-10-11 5 views
0

는 다음 스크립트를 감안할 때 :ConfigParser가 디스크에 즉시 쓰지 않는 이유는 무엇입니까?

$ touch test.conf 
$ python tests.py # this is what I've named the above 
$ $ cat test.conf 
[test] 
2012-10-10_231439 = oh hey there 

그러나 당신이 time.sleep (1) 모든 항목의 주석을 해제하는 경우 :에 의해 그림과 같이 그것은 단지, 파일에 하나 개의 항목을 작성합니다

import ConfigParser 
from datetime import datetime 
import time 

def write_stuff(): 
    section = "test" 
    item = "oh hey there" 
    conf_filename = "test.conf" 

    conf = ConfigParser.ConfigParser() 
    conf.readfp(open(conf_filename, 'r', 0)) 

    timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S") 

    conf.set(section, timestamp, item) 

    with open(conf_filename, "w", 0) as conf_file: 
     # time.sleep(1) 
     conf.write(conf_file) 

write_stuff() 
write_stuff() 
write_stuff() 
write_stuff() 

나타나다. 이상하게도 (어쨌든, 나에게) write_stuff()를 한 번 호출하고 쉘에서 스크립트를 빠르게 연속적으로 호출하면이 문제가 발생합니다. 일단 파이썬이 종료되면 디스크에 무엇이든지 디스크에 저장 될 것이라고 생각합니다. 무슨 일이야?

환경 : 파이썬 2.7.3 맥 OS X에서 10.8

답변

3

여기에서 문제는 구성 파일에서 사용중인 키 값이 인 의 시간 스탬프입니다. 즉, write_stuff() 번을 연속으로 4 번 호출하면 시간이 변경되지 않고 시간 스탬프가 변경되지 않고 새 값을 추가하는 대신 이전 값을 덮어 쓰게됩니다.

매번 고유 한 키 값을 생성하면됩니다. 당신이 타임 스탬프 값을 유지하려면, 어떤이 작동합니다 :

count = 0 

def write_stuff(): 
    global count 

    section = "test" 
    item = "oh hey there" 
    conf_filename = "test.conf" 

    conf = ConfigParser.ConfigParser() 
    conf.readfp(open(conf_filename, 'r', 0)) 

    timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")+ "_%s" % count 
    count += 1 

    conf.set(section, timestamp, item) 

    with open(conf_filename, "w", 0) as conf_file: 
     conf.write(conf_file) 

참고, 설정 파일에 기록 된 값을 특정 순서로하지 않습니다.

+0

* facepalm * 나는 그 말이 맞다고 생각한다 :) 고마워. –

2

당신은을 통해 동일한 항목을 작성 이상 againg, 파일 추가하는 대신 "w""a"을 사용하고 있습니다 : 당신이 원하는

with open("test.txt", "a") as myfile: 
    myfile.write("appended text") 

Mybe을

config.add_section('Section1') 
config.set('Section1', 'an_int', '15') 
config.set('Section1', 'a_bool', 'true') 
config.set('Section1', 'a_float', '3.1415') 
config.set('Section1', 'baz', 'fun') 
config.set('Section1', 'bar', 'Python') 
config.set('Section1', 'foo', '%(bar)s is %(baz)s!') 

# Writing our configuration file to 'example.cfg' 
with open('example.cfg', 'wb') as configfile: 
    config.write(configfile) 

O : this 같은 섹션이 한 번 인쇄됩니다, 그리고 당신이 그것에 여러 항목을 추가 할 수 있도록하는 utput :

[Section1] 
bar = Python 
baz = fun 
a_bool = true 
an_int = 15 
foo = %(bar)s is %(baz)s! 
a_float = 3.1415 

위에서 보셨 듯이 함수를 여러 번 호출하지 않고 한 번 쓰기 만하면됩니다.

+2

Append 모드로 열면 config가 파일뿐만 아니라 Item에 4 번 기록됩니다. 나는 그것이 올바른 해결책이라고 생각하지 않습니다. –

+0

write_stuff()를 4 번 사용하면 4 번 쓸 수 있습니다 ... 달성하려는 것은 무엇입니까? 이해하기 어려운 순간에 원하는 결과로 질문을 편집하십시오. – root

관련 문제