2012-06-21 3 views
0

헤이 화려한 마음 거기, 내가 일하는 발견이 파이썬 스크립트를 얻으려고하고 알아낼 수 없습니다스크립트

병합 목소리로 코드의 마지막 줄에 구문 에러를 얻기 또는 원래의 포스터가 코드를 제대로받지 못했다면. 이 스크립트는 일치 파일에서 merge 명령을 사용하여 충돌하는 두 파일을 가져 와서 그 중 하나를 파일 이름의 날짜 스탬프로 복제하여 Unison에서 자동 충돌 해결을 사용하도록되어 있습니다. 원래 posing is here하지만 들여 쓰기가 없었으므로 팝업 오류를보고 수동으로 수행해야했습니다. 내가 지금 당장 벗어날 수없는 오류는

File "/bin/unison_merge.py", line 5, in <module> 
     PATH, CURRENT1, CURRENT2, NEW = sys.argv[1:] 
ValueError: need more than 0 values to unpack 

내가 밖으로 도울 수있을 것이라고 기대하고있다.

아래의 스크립트 전체가 도움이 될 것이라는 희망으로 포함 시켰습니다. 다른 오류도 발견 될 것입니다. :).

#!/usr/bin/env python2.7 

import sys, os, datetime, os, filecmp 

PATH, CURRENT1, CURRENT2, NEW = sys.argv[1:] 

# see http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#merge 

promote_remote = False 
backup_file_color = "red" 

def is_suffix(a, b): return b[-len(a):] == a 

def merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote): 
# CURRENT1 is copy of local, CURRENT2 is copy of remote 

    if filecmp.cmp(CURRENT1, CURRENT2, shallow = False): 
# special case -- files have same contents 
# not a real conflict. just use local copy, no backup 
     print "merge of identical files" 
    os.link(CURRENT1, NEW) 
    return 

# PATH is relative to unison root. 
# We need to know absolute path. 
# We get it, assuming CURRENT1 is an absolute path 
# referring to a file in the same subdirectory as PATH. 

assert CURRENT1[0] == '/', "CURRENT1 (%s) is not absolute path" % CURRENT1 

PATH_dir, PATH_tail = os.path.split(PATH) 
ABS_dir = os.path.dirname(CURRENT1) 

assert is_suffix(PATH_dir, ABS_dir), "%s not suffix of %s!" % (PATH_dir, ABS_dir) 

ABS_PATH = os.path.join(ABS_dir, PATH_tail) 

timestamp = datetime.datetime.now().strftime("%y%m%d_%H%M") 
(root, ext) = os.path.splitext(PATH_tail) 
for counter in range(100): 
    counter = " %d" % counter if counter else "" 
    filename = "%s @%s%s%s" % (root, timestamp, counter, ext) 
    BACKUP = os.path.join(ABS_dir, filename) 
    if not os.path.exists(BACKUP): break 
else: 
    assert False, "too many existing backups %s" % BACKUP 

# promote_remote = False 
# seems to retain file props, saving update in next sync? 

    print "CONFLICT:", ABS_PATH 

if promote_remote: 
# resolve conflict by using remote copy, while backing up local to 
    BACKUP 
    CURRENT1, CURRENT2 = CURRENT2, CURRENT1 
    print "CONFLICT remote saved as", filename 
else: 
    print "CONFLICT local saved as", filename 

assert os.path.isfile(CURRENT1) 
assert not os.path.exists(NEW) 
assert not os.path.exists(BACKUP) 

os.link(CURRENT1, BACKUP) 
os.link(CURRENT2, NEW) 

if backup_file_color and backup_file_color != 'none': 
    mac_color_file(BACKUP, backup_file_color) 

# note: coloring the tmp file NEW is useless - not propagated 
# coloring the current file ABS_PATH causes UNISON to complain 

# chmod -w BACKUP 
# os.chmod(BACKUP, stat.S_IRUSR) 

# just for coloring file in mac Finder 
def mac_color_file(file, color): 
    if not os.path.exists("/usr/bin/osascript"): return 
color_map = { 
"none":0, 
"orange":1, 
"red":2, 
"yellow":3, 
"blue":4, 
"purple":5, 
"green":6, 
"gray":7, 
} 
assert color in color_map 
assert file[0] == '/', 'absolute path required' 
assert os.path.exists(file) 
#see http://stackoverflow.com/questions/2435580/tagging-files-with-colors-in-os-x-finder-from-shell-scripts 
#osascript -e "tell application \"Finder\" to set label index of alias POSIX 
file ("$filename\" to $label") 
cmd = '''/usr/bin/osascript -e 'tell application "Finder" to set label index of alias POSIX file "%s" to %d' > /dev/null ''' % (file, color_map[color]) 
try: 
    retcode = subprocess.call(cmd, shell=True) 
    if retcode < 0: 
     print >>sys.stderr, "mac_color_file child was terminated by signal", retcode 
    elif retcode > 0: 
     print >>sys.stderr, "mac_color_file child returned", retcode 
except OSError, e: 
    print >>sys.stderr, "mac_color_file child failed:", e 

### main ### 

merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote) 

답변

0

여기에 현재 스크립트입니다. 조화 문서에 설명 된대로 네 개의 인수로 호출 될 것으로 예상됩니다. 를 트리거하려면 .prf 파일을 사용자의 조화에 다음과 같은 줄을 추가 :

merge = Name * -> /Users/neal/Bin/daemons/unison_merge.py 'PATH' CURRENT1 CURRENT2 NEW 

는 단일 따옴표 (?했다) 필요 한마음으로 버그를 해결한다.

#!/usr/bin/env python2.7 

# see http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#merge 

import sys, os, datetime, os, stat, subprocess, filecmp 

# log = open("/Users/neal/unison_merge.log", "a") 
# sys.stdout = log 
# sys.stderr = log 

# work around bug in unison adds quotes incorrectly 
# something to do with blanks in filenames 

def clean(x): 
    if len(x) < 3: return x 
    if x[0] == "'": x = x[1:] 
    if x[-1] == "'": x = x[:-1] 
    return x 

sys.argv = [clean(x) for x in sys.argv] 

try: 
    PATH, CURRENT1, CURRENT2, NEW = sys.argv[1:] 
except: 
    print "usage: ", " ".join("[%s]" % x for x in sys.argv) 
    raise 

backup_file_color = 'red' # for mac 
promote_remote = False 

def is_suffix(a, b): return b[-len(a):] == a 

def mac_color_file(file, color): 
    if not os.path.exists("/usr/bin/osascript"): return 
    color_map = { 
     "none":0, 
     "orange":1, 
     "red":2, 
     "yellow":3, 
     "blue":4, 
     "purple":5, 
     "green":6, 
     "gray":7, 
     } 
    assert color in color_map 
    assert file[0] == '/', 'absolute path required' 
    assert os.path.exists(file) 
    #see http://stackoverflow.com/questions/2435580/tagging-files-with-colors-in-os-x-finder-from-shell-scripts 
    #osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"$filename\" to $label" 
    cmd = '''/usr/bin/osascript -e 'tell application "Finder" to set label index of alias POSIX file "%s" to %d' > /dev/null ''' % (file, color_map[color]) 
    try: 
     retcode = subprocess.call(cmd, shell=True) 
     if retcode < 0: 
      print >>sys.stderr, "mac_color_file child was terminated by signal", -retcode 
     elif retcode > 0: 
      print >>sys.stderr, "mac_color_file child returned", retcode 
    except OSError, e: 
     print >>sys.stderr, "mac_color_file child failed:", e 

def merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote): 
    # CURRENT1 is copy of local, CURRENT2 is copy of remote 

    # PATH is relative to unison root. 
    # We need to know absolute path. 
    # We get it, assuming CURRENT1 is an absolute path 
    # referring to a file in the same subdirectory as PATH. 

    if filecmp.cmp(CURRENT1, CURRENT2, shallow = False): 
     # special case -- files have same contents 
     # not a real conflict. just use local copy, no backup 
     print "merge of identical files" 
     os.link(CURRENT1, NEW) 
     return 

    assert CURRENT1[0] == '/', "CURRENT1 (%s) is not absolute path" % CURRENT1 

    PATH_dir, PATH_tail = os.path.split(PATH) 
    ABS_dir = os.path.dirname(CURRENT1) 

    assert is_suffix(PATH_dir, ABS_dir), "%s not suffix of %s!" % (PATH_dir, ABS_dir) 

    ABS_PATH = os.path.join(ABS_dir, PATH_tail) 

    timestamp = datetime.datetime.now().strftime("%y%m%d_%H%M") 
    (root, ext) = os.path.splitext(PATH_tail) 
    for counter in range(100): 
     counter = " %d" % counter if counter else "" 
     filename = "%s @%s%s%s" % (root, timestamp, counter, ext) 
     BACKUP = os.path.join(ABS_dir, filename) 
     if not os.path.exists(BACKUP): break 
    else: 
     assert False, "too many existing backups %s" % BACKUP 

    # promote_remote = False 
    # seems to retain file props, saving update in next sync? 

    print "CONFLICT:", ABS_PATH 

    if promote_remote: 
     # resolve conflict by using remote copy, while backing up local to BACKUP 
     CURRENT1, CURRENT2 = CURRENT2, CURRENT1 
     print "CONFLICT remote saved as", filename 
    else: 
     print "CONFLICT local saved as", filename 

    assert os.path.isfile(CURRENT1) 
    assert not os.path.exists(NEW) 
    assert not os.path.exists(BACKUP) 

    os.link(CURRENT1, BACKUP) 
    os.link(CURRENT2, NEW) 

    if backup_file_color and backup_file_color != 'none': 
     mac_color_file(BACKUP, backup_file_color) 

    # note: coloring the tmp file NEW is useless - not propagated 
    # coloring the current file ABS_PATH causes UNISON to complain 

    # chmod -w BACKUP 
    # os.chmod(BACKUP, stat.S_IRUSR) 

### main ### 

try: 
    merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote) 
except Exception as e: 
    print >>sys.stderr, "ERROR in unison_merge.py" 
    print >>sys.stderr, "ERROR:", str(e) 
0
+0

으악, 왼쪽 밖으로 비트 :

여기 스크립트입니다. 하지만 지금 내가보고있는 오류는 파일 "/bin/unison_merge.py", 줄 5, PATH, CURRENT1, CURRENT2, NEW = sys.argv [1 :] ValueError : 0보다 큰 값이 필요합니다. 압축을 풀려면 – smithjw

+0

@smithjw : 프로그램은 언급 된 변수에 압축을 풀어주는 4 개의 명령 행 입력이 필요합니다. – pyfunc

0

이 단지 절반 마음 시도 :

이 튜토리얼 페이지는 try..except 구조의 사용을 명확히.

들여 쓰기가 정말로 꺼졌으며 프로그램에서 무엇을하려고하는지 잘 모르겠습니다.

나는 하나의 커다란 기능이 시작되기를 바랍니다.

명령 줄에서 프로그램을 실행하려면 명령 줄 인수를 제공해야합니다. 이 경우

python test.py x y c v 

:

PATH, CURRENT1, CURRENT2, NEW = 'x', 'y', 'c', 'z' 

프로그램은

#!/usr/bin/env python2.7 

import sys, os, datetime, os, filecmp 

print sys.argv 
PATH, CURRENT1, CURRENT2, NEW = sys.argv[1:] 

# see http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#merge 

promote_remote = False 
backup_file_color = "red" 

def is_suffix(a, b): 
    return b[-len(a):] == a 

def merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote): 
    # CURRENT1 is copy of local, CURRENT2 is copy of remote 

    if filecmp.cmp(CURRENT1, CURRENT2, shallow = False): 
    # special case -- files have same contents 
    # not a real conflict. just use local copy, no backup 
     print "merge of identical files" 
     os.link(CURRENT1, NEW) 
     return 

    # PATH is relative to unison root. 
    # We need to know absolute path. 
    # We get it, assuming CURRENT1 is an absolute path 
    # referring to a file in the same subdirectory as PATH. 

    assert CURRENT1[0] == '/', "CURRENT1 (%s) is not absolute path" % CURRENT1 

    PATH_dir, PATH_tail = os.path.split(PATH) 
    ABS_dir = os.path.dirname(CURRENT1) 

    assert is_suffix(PATH_dir, ABS_dir), "%s not suffix of %s!" % (PATH_dir, ABS_dir) 

    ABS_PATH = os.path.join(ABS_dir, PATH_tail) 

    timestamp = datetime.datetime.now().strftime("%y%m%d_%H%M") 
    (root, ext) = os.path.splitext(PATH_tail) 
    for counter in range(100): 
     counter = " %d" % counter if counter else "" 
     filename = "%s @%s%s%s" % (root, timestamp, counter, ext) 
     BACKUP = os.path.join(ABS_dir, filename) 
     if not os.path.exists(BACKUP): 
      break 
     else: 
      assert False, "too many existing backups %s" % BACKUP 

    # promote_remote = False 
    # seems to retain file props, saving update in next sync? 

    print "CONFLICT:", ABS_PATH 

    if promote_remote: 
     # resolve conflict by using remote copy, while backing up local to BACKUP 
     CURRENT1, CURRENT2 = CURRENT2, CURRENT1 
     print "CONFLICT remote saved as", filename 
    else: 
     print "CONFLICT local saved as", filename 

    assert os.path.isfile(CURRENT1) 
    assert not os.path.exists(NEW) 
    assert not os.path.exists(BACKUP) 

    os.link(CURRENT1, BACKUP) 
    os.link(CURRENT2, NEW) 

    if backup_file_color and backup_file_color != 'none': 
     mac_color_file(BACKUP, backup_file_color) 

    # note: coloring the tmp file NEW is useless - not propagated 
    # coloring the current file ABS_PATH causes UNISON to complain 

    # chmod -w BACKUP 
    # os.chmod(BACKUP, stat.S_IRUSR) 

    # just for coloring file in mac Finder 
    def mac_color_file(file, color): 
     if not os.path.exists("/usr/bin/osascript"): 
     return 

    color_map = { 
    "none":0, 
    "orange":1, 
    "red":2, 
    "yellow":3, 
    "blue":4, 
    "purple":5, 
    "green":6, 
    "gray":7, 
    } 

    assert color in color_map 
    assert file[0] == '/', 'absolute path required' 
    assert os.path.exists(file) 
    #see http://stackoverflow.com/questions/2435580/tagging-files-with-colors-in-os-x-finder-from-shell-scripts 
    #osascript -e "tell application \"Finder\" to set label index of alias POSIX 
    file ("$filename\" to $label") 
    cmd = '''/usr/bin/osascript -e 'tell application "Finder" to set label index of alias POSIX file "%s" to %d' > /dev/null ''' % (file, color_map[color]) 

    try: 
     retcode = subprocess.call(cmd, shell=True) 
     if retcode < 0: 
      print >>sys.stderr, "mac_color_file child was terminated by signal", retcode 
     elif retcode > 0: 
      print >>sys.stderr, "mac_color_file child returned", retcode 
    except: 
     pass 

if __file__ == '__main__': 
    merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote) 
+0

시도해 줘서 고맙지 만 들여 쓰기가 훨씬 나아졌지만 여전히 5 행을 참조하여 'ValueError : 너무 많은 값을 풀어서'를 참조하십시오. – smithjw

+0

@smithjw : 언급 한 바와 같이 명령 줄 인수를 제공해야합니다. 다음과 같이 프로그램을 실행합니다 : python test.py x y c v – pyfunc

+0

나는 파일 이름을 바꾸고 복제하기 위해 'PATH CURRENT1 CURRENT2 NEW'를 스크립트에 전달해야하는 Unison을 통해 실행 중입니다. – smithjw