2014-11-09 3 views
1

내 프로그램 종료 후 itertools.product() 상태를 저장하고 싶습니다. 산 세척과 함께 이것을 할 수 있습니까? 내가 할 계획은 순열을 생성하고 프로세스가 중단되면 (KeyboardInterrupt) 다음에 프로그램을 실행할 때 프로세스를 다시 시작할 수 있습니다. 파이썬 2에서itertools.product를 python으로 피클 할 수 있습니까?

def trywith(itr): 
    try: 
     for word in itr: 
      time.sleep(1) 
      print("".join(word)) 
    except KeyboardInterrupt: 
     f=open("/root/pickle.dat","wb") 
     pickle.dump((itr),f) 
     f.close() 

if os.path.exists("/root/pickle.dat"): 
    f=open("/root/pickle.dat","rb") 
    itr=pickle.load(f) 
    trywith(itr) 
else: 
    try: 
     itr=itertools.product('abcd',repeat=3) 
     for word in itr: 
      time.sleep(1) 
      print("".join(word)) 
    except KeyboardInterrupt: 
     f=open("/root/pickle.dat","wb") 
     pickle.dump((itr),f) 
     f.close() 
+0

이 http://stackoverflow.com/q에서보세요 :

그러나, 파이썬 3에서, 산세 지원이 추가되었습니다, 그래서 itertools.product() 반복자는 잘 피클한다고/9864809/3001761 – jonrsharpe

+0

니스 (Nice)하지만 아직 파이썬을 탐색 중이므로이 작업을 수행하는 방법에 대한 간단한 설명을 찾고있었습니다. – repzero

+0

짧은 대답은 '아니오'입니다. 훨씬 간단한 해결책이 없다고 생각하지 않습니다. – jonrsharpe

답변

0

는 다양한 itertools에 대한 피클 지원이되지 않습니다.

>>> import pickle 
>>> import itertools 
>>> it = itertools.product(range(2), repeat=3) 
>>> next(it) 
(0, 0, 0) 
>>> next(it) 
(0, 0, 1) 
>>> next(it) 
(0, 1, 0) 
>>> p = pickle.dumps(it) 
>>> del it 
>>> it = pickle.loads(p) 
>>> next(it) 
(0, 1, 1) 
>>> next(it) 
(1, 0, 0) 
>>> next(it) 
(1, 0, 1) 
>>> next(it) 
(1, 1, 0)