2017-11-06 5 views
0

다음과 같이 python 스크립트가 있습니다. 이 스크립트에서는 파일의 stdoutstderr을 수집하여 Linux에 저장합니다. 이 스크립트에서 for 루프 이후에 서브 프로세스 호출이 파이썬에서 완료되었습니다.

, 나는이 스크립트에서 input_file 을 통해 루프 기능 path_finder를 실행하고, 나는 다른 위치로 Linux에 데이터를 이동 subprocess을 사용하고 있습니다.

나는이 subprocess 호출이 loop가 끝난 후 실행하려는 대신,이 때 처음으로 loop 실행되고 loop 그것을 실행하는 두 번째 시간이 예상되는 오류가 발생하면 실행됩니다. 파일이 존재하면 오류가 발생합니다.

#!/usr/bin/python 

import os 
import sys 
import traceback 
import subprocess 

def path_finder(
    table, 
    mysql_user, 
    user, 
    dir, 
    ): 


    day = datetime.now().strftime('%Y-%m-%d') 
    month = datetime.now().strftime('%Y-%m') 

    Linux_path = '/data/logging/{}'.format(input_file) 
    New_path = '/user/{}/{}/logging/{}/{}/{}'.format(user,dir,mysql_user,month,day) 

    subprocess.call(["rm", Linux_path]) 

    so = se = open('/data/logging/{}'.format(input_file), 'a', 
        0) 

    #re-open stdout without buffering 
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'a', 0) 

    # redirect stdout and stderr to the log file opened above 
    os.dup2(so.fileno(), sys.stdout.fileno()) 
    os.dup2(se.fileno(), sys.stderr.fileno()) 

    ### CODE: 

    Do something 

    ### if errors the print traceback 

    ### repeat the same for every table in input file 

    ## Execute below statement after for loop completed 

    subprocess.call(["cp", Linux_path, New_path]) 


if len(sys.argv) != 5: 
    print 'Invalid number of args......' 
    exit() 

input_file = sys.argv[1] 
mysql_user = sys.argv[2] 
user = sys.argv[3] 
dir = sys.argv[4] 

input = open("{}.format(input_file)", "r") 

for table in input: 
    path_finder(
      table, 
      mysql_user, 
      user, 
      dir, 
      ) 

sc.stop() 
print 
sub process 호출이 for loop 이후에 실행되도록 어떻게 내 스크립트를 변경할 수 있습니다

수행됩니다 ?

답변

1

문제가 무엇인지 모르겠습니다. 마지막으로 실행하고자하는 명령문은 현재 'path_finder'함수에 존재하며 매번 실행되는 이유입니다. 이 작업을 한 번만 실행하고 for 루프가 끝난 후에는 그 뒤에 문을 넣으십시오.

for table in input: 
path_finder(
     table, 
     mysql_user, 
     user, 
     dir, 
     ) 
subprocess.call(["cp", Linux_path, New_path]) 

이렇게해야합니다.