삼성 스마트TV를 제대로 사용해보기 위해서 AllShare 기능을 설정해보고자 했다.
최근에는 삼성링크라는 이름으로 제공해주고 있는 서비스다.

그러나 사실 원하는 만큼의 깔끔함이나 원활한 기능을 제공해주고 있지는 못하고 있고
더군다나 최근에는 거의 버린 서비스라는 느낌이 확~

음... 내가 이런 말을 하면 안되는데.... 음... 안되는데...

뭐 여하튼...

그래서 해당 기능을 서버에서 제거해버렸는데 여전히 남아있는 흔적이 있었다.
동영상 파일마다 삼성링크가 만들어낸 [ *.mta ] 파일들이 바로 그것이다.


해당 파일들을 찾아서 지우는 일을 하고 싶어서... Python을 이용해보려 했다.


1. Windows 환경에서 Python 실행하기

   - http://whatwant.tistory.com/703 
 

2. 스크립트 만들기

   - 아래와 같이 간단한 스크립트로 찾아서 지웠다.


#!/usr/bin/python

# -*- coding: utf-8 -*-


import os

import sys


EXT = '.mta'


if __name__ == "__main__":


        if len(sys.argv) < 2:

                sys.exit('Usage: %s path' % sys.argv[0])

        if not os.path.isdir(sys.argv[1]):

                sys.exit('ERROR: %s was not found!' % sys.argv[1])

        PATH_TARGET = sys.argv[1]


        for root, dirs, files in os.walk( PATH_TARGET ):


                for file in files:

                        ext = os.path.splitext( file )

                        if EXT == ext[1]:

                                os.remove( os.path.join(root,file) )


        exit()



   - 예외 사항 등에 대한 고려가 없었기에 위험한 코드일 수도 있다. 주의!!!

 
반응형

개인적으로 업무용 운영체제로는 리눅스가 가장 좋다고 생각하기에
윈도우즈 환경에 대해서는 그다지 알아보지도 않고 사용하지도 않고 있다.

회사에서도 우분투를 메인 운영체제로 사용하고 있고 필요에 따라 VirtualBox로 윈도우즈 환경을 사용하고 있다.
VBox의 윈도우즈 환경을 사용하긴 하지만, 공용폴더를 이용하여 중요한 파일 관리는 모두 우분투 환경에서 하고 있다.

그래서 지금까지는 파일을 다루거나 하는 스크립트를
그냥 파이썬(Python)으로 만들어서 사용하는데 아무런 문제가 없었다.


그런데, 최근 미니서버를 돌리면서 여러가지 이슈로 윈도우즈 환경을 구축했는데,
해당 서버에서 어떤 파일을 다뤄야 하는 스크립트가 필요한데...
윈도우즈 환경이다보니 파이썬 실행환경을 맞춰줘야 하게 되어서 알아보고자 한다.


공식홈페이지
   - https://www.python.org/


윈도우즈 환경을 위한 패키지도 제공을 해주고 있다.
3.x 버전과 2.x 버전을 제공해주고 있는데... 호환성을 위해 2.x 버전으로 설치를 하자.

설치할 때에 PATH 부분도 추가를 해주는 것이 편리하다.



설치가 모두 잘 되면, 실행해보자.


위와 같이 빠져나올 때엔 "exit()"를 실행하면 된다.


반응형

GitPython을 가지고 뭔가 만들다가 에러를 만났다.


fetch()를 실행하는데, 뭔가가 맞지 않다고 에러라고 하는데... 아무리 살펴봐도 에러가 발생한 상황이 아닌데...
그래서 찾아봤는데 이는 GitPython이 최신 버전의 Git 과의 궁합에서 발생한 에러/버그 상황이다.

   https://github.com/gitpython-developers/GitPython/issues/142

해결 방법은 파일 수정이라고 한다.

$ sudo nano /usr/local/lib/python2.7/dist-packages/GitPython-0.3.2.RC1-py2.7.egg/git/remote.py

...
        def _get_fetch_info_from_stderr(self, proc, progress):
                # skip first line as it is some remote info we are not interested in
                output = IterableList('name')

                # lines which are no progress are fetch info lines
                # this also waits for the command to finish
                # Skip some progress lines that don't provide relevant information
                fetch_info_lines = list()
                for line in digest_process_messages(proc.stderr, progress):
                        if line.startswith('From') or line.startswith('remote: Total'):
                                continue
                        elif line.startswith('warning:'):
                                print >> sys.stderr, line
                                continue
...

위와 같은 코드를 아래와 같이 변경하면 된다고 한다.

...
        def _get_fetch_info_from_stderr(self, proc, progress):
                # skip first line as it is some remote info we are not interested in
                output = IterableList('name')

                # lines which are no progress are fetch info lines
                # this also waits for the command to finish
                # Skip some progress lines that don't provide relevant information
                fetch_info_lines = list()
                for line in digest_process_messages(proc.stderr, progress):
                        #if line.startswith('From') or line.startswith('remote: Total'):
                        if line.startswith('From') or line.startswith('remote: Total') \
                                or line.startswith('POST') or line.startswith(' ='):
                                continue
                        elif line.startswith('warning:'):
                                print >> sys.stderr, line
                                continue
...

그런데, 위와 같이 하여도 에러는 여전하였다.

Git을 다룬다는 것 자체도 좀 마이너하고, 특히나 GitPython을 다루는 분들이 많지 않고...
자료를 찾기가 너무 어려워서 다시 원점으로 돌아가서 현재 개발중인 코드를 살펴보다가 답을 찾았다.

...
                # read head information
                fp = open(join(self.repo.git_dir, 'FETCH_HEAD'),'r')
                fetch_head_info = fp.readlines()
                fp.close()

                assert len(fetch_info_lines) == len(fetch_head_info), "len(%s) != len(%s)" % (fetch_head_info, fetch_info_lines)

                output.extend(FetchInfo._from_line(self.repo, err_line, fetch_line)
                                                for err_line,fetch_line in zip(fetch_info_lines, fetch_head_info))

                finalize_process(proc)
                return output
...

에러메시지를 출력하는 부분이 위와 같이 있는데, 그냥 확 주석처리해버리면 된다.

...
        # read head information
        fp = open(join(self.repo.git_dir, 'FETCH_HEAD'),'r')
        fetch_head_info = fp.readlines()
        fp.close()
       
        # NOTE: HACK Just disabling this line will make github repositories work much better.
        # I simply couldn't stand it anymore, so here is the quick and dirty fix ... .
        # This project needs a lot of work !
        # assert len(fetch_info_lines) == len(fetch_head_info), "len(%s) != len(%s)" % (fetch_head_info, fetch_info_lines)
       
        output.extend(FetchInfo._from_line(self.repo, err_line, fetch_line)
                        for err_line,fetch_line in zip(fetch_info_lines, fetch_head_info))
...

프로젝트 담당자도 인정했다시피 이렇게 주석처리하는 것이 정석은 아니다.
여력이 되시는 분은 이 부분에 대해서 도움을 주면 좋을 것 같다.


뭐 여하튼... 문제 해결!!!

반응형

Git의 데이터들을 다루기 위해서 Python을 이용해서 스크립트를 종종 만들고 있다.

지금까지는 subprocess를 사용해서
외부 명령어(git)를 실행하고 그 결과를 String으로 받아서 파싱하는 방식으로 만들었는데...
(혼자서 나만의 Git Class를 만들어서, 쿵짝쿵짝... ^^)


Python Library로 제공되는 것이 있지 않을까 좀 찾아보았더니... 당연히(?) 있다!

GitPython 0.3.2 RC1 (Python Git Library) : 2011-07-06
   https://pypi.python.org/pypi/GitPython/0.3.2.RC1

Package Documentation
   GitPython is a python library used to interact with Git repositories.

Author                            : Sebastian Thiel, Michael Trier
Documentation                : GitPython package documentation
Home Page                     : http://gitorious.org/projects/git-python/
License                          : BSD License
Requires                         : gitdb (>=0.5.1)
Package Index Owner      : Sebastian.Thiel, mtrier
Package Index Maintainer : Sebastian.Thiel
DOAP record                   : GitPython-0.3.2.RC1.xml

gitdb 0.5.4 (Git Object Database) : 2011-07-05
   https://pypi.python.org/pypi/gitdb

Package Documentation
   GitDB is a pure-Python git object database

Author                       : Sebastian Thiel
Documentation           : gitdb package documentation
Home Page                : https://github.com/gitpython-developers/gitdb
License                     : BSD License
Requires                    : async (>=0.6.1), smmap (>=0.8.0)
Package Index Owner : Sebastian.Thiel
DOAP record              : gitdb-0.5.4.xml


Ubuntu를 사용하게 되면 정말 편리한 점 중에서 한 가지가 바로 Package 관리인데...
주어진대로 사용을 하면 편리하지만, 직접 설치해서 뭔가 하려하면 오히려 번거로운 부분도 많다.

Python도 마찬가지인데 Python과 관련된 전부를 다운로드 받아서 직접 설치한 것이 아니라면
그 외 나머지들도 그냥 패키지로 설치하는 것이 편리하다.

위의 라이브러리들도 마찬가지인데...
이미 Python을 Ubuntu에서 제공하는 패키지로 설치해서 사용하고 있기에,
그냥 Ubuntu에서 제공해주는 패키지로 설치를 해보려고 했는데...

아래와 같이 하면 설치는 되는데... Ubuntu 버전에 따라 제공하는 버전이 다르다.

$ sudo apt-get install python-git

현재(2014.06) 제공하는 버전은 아래와 같다.

 Version  Release   python-git version 
 14.04  Trusty Tahr  0.3.2~RC1-3 
 13.10  Saucy Salamander  0.3.2~RC1-2 
 13.04  Raring  0.3.2~RC1-1
 12.04  Precise Pangolin  0.1.6-1
 10.04  Lucid Lynx  0.1.6-1 

위와 같이 설치하면 편하기는 하지만, 쓸데없는(?) 부가 패키지들도 같이 설치를 한다.

$ sudo apt-get install python-git
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다      
상태 정보를 읽는 중입니다... 완료
다음 패키지를 더 설치할 것입니다:
  git git-man liberror-perl libjs-jquery python-async python-gitdb python-smmap
제안하는 패키지:
  git-daemon-run git-daemon-sysvinit git-doc git-el git-email git-gui gitk gitweb git-arch git-bzr
  git-cvs git-mediawiki git-svn javascript-common
다음 새 패키지를 설치할 것입니다:
  git git-man liberror-perl libjs-jquery python-async python-git python-gitdb python-smmap
0개 업그레이드, 8개 새로 설치, 0개 제거 및 0개 업그레이드 안 함.
3,780 k바이트 아카이브를 받아야 합니다.
이 작업 후 23.5 M바이트의 디스크 공간을 더 사용하게 됩니다.
계속 하시겠습니까? [Y/n]

특히 git과 관련한 패키지들도 설치를 하게 되는데, git을 source로 직접 설치한 경우 불필요하고 번거롭기만 하다.


그러면, python-git을 개별 설치하려면 어떻게 해야할까?!
원하는 최신 버전으로 설치하기 위해서는 다음과 같이 수행하자.

$ sudo apt-get install python-setuptools python-dev
$ sudo easy_install GitPython

간단하다.
현재(2014.06) 설치되는 버전은 '0.3.2~RC1'이다.



잘 동작하는지 테스트를 해보기 위해서는 다음과 같이 해보자.



아래 샘플 코드로 돌려보자~

#!/usr/bin/python
# -*- coding: utf-8 -*-

import git
import os
import sys
import time

if __name__ == "__main__":

        #for i in range(len(sys.argv)):
        #       print "sys.argv[%d] = '%s'" % (i, sys.argv[i])

        #repo = git.Repo.clone_from( URL_SOURCE, PATH_TARGET )


        if len(sys.argv) < 2:
                sys.exit('Usage: %s repository-name' % sys.argv[0])

        if not os.path.isdir(sys.argv[1]):
                sys.exit('ERROR: Repository %s was not found!' % sys.argv[1])


        PATH_TARGET = sys.argv[1]
        repo = git.Repo( PATH_TARGET )

        for remote in repo.remotes:
                print "[ " + str(remote) + " branches ]"

                for branch in getattr(repo.remotes, str(remote)).refs:
                        print " " + str(branch).replace( str(remote)+"/", "" )

                        for commit in repo.iter_commits(branch, max_count=3):

                                print ""
                                print "         Commit          : ", commit
                                print "         Author          : ", commit.author, ", (",
                                print time.asctime(time.gmtime(commit.authored_date)), ")"
                                print "         Committer       : ", commit.committer, ", (",
                                print time.asctime(time.gmtime(commit.committed_date)), ")"
                                print "         Encoding        : ", commit.encoding
                                print "         Summary         : ", commit.summary
                                print "         Delta LOC       : ", commit.stats.total['lines'], " (+",
                                print commit.stats.total['insertions'], ", -",
                                print commit.stats.total['deletions'], ")"
                                #print commit.stats.files
                                #print "                Message         : ", commit.message
                                #print "                Parents         : ", commit.parents

        print ""

        print "[ Local branches ]"
        for branch in repo.branches:
                print " " + str(branch)

                #commits = list( repo.iter_commits(branch, max_count=10) )

                for commit in repo.iter_commits(branch, max_count=3):

                        print ""
                        print "         Commit          : ", commit
                        print "         Author          : ", commit.author, ", (",
                        print time.asctime(time.gmtime(commit.authored_date)), ")"
                        print "         Committer       : ", commit.committer, ", (",
                        print time.asctime(time.gmtime(commit.committed_date)), ")"
                        print "         Encoding        : ", commit.encoding
                        print "         Summary         : ", commit.summary
                        print "         Delta LOC       : ", commit.stats.total['lines'], " (+",
                        print commit.stats.total['insertions'], ", -",
                        print commit.stats.total['deletions'], ")"
                        #print commit.stats.files
                        #print "                Message         : ", commit.message
                        #print "                Parents         : ", commit.parents


공식 매뉴얼과 가이드는 다음에서 확인할 수 있다.

   http://pythonhosted.org/GitPython/0.3.2/tutorial.html
   http://pythonhosted.org/GitPython/0.3.2/reference.html

반응형


Python script 파일을 만들어서 실행을 하다보면,
script 파일이 지금 현재 어느 경로에 위치하고 있는지 알고 싶은 경우가 있다.

이럴 때 사용할 수 있는 좋은 예약어가 하나 있다.

__file__


현재 실행 중인 스크립트 파일 이름을 의미한다.
단순한 파일 이름이 아니라 실행할 때 사용한 경로를 포함한 파일 이름이다.

테스트를 위해서 [ dir.py ]라는 이름의 Python script 파일을 다음 내용으로 생성해보자.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os

if __name__ == "__main__":

        print "__file__                                                       = " + __file__
        print "os.path.dirname(__file__)                              = " + os.path.dirname(__file__)
        print "os.path.realpath(__file__)                              = " + os.path.realpath(__file__)
        print "os.path.realpath( os.path.dirname(__file__) )   = " + os.path.realpath( os.path.dirname(__file__) )
        print
        print "os.getcwd()                                                 = " + os.getcwd()
        print
        print "os.path.basename( os.path.realpath(__file__) ) = " + os.path.basename(__file__)


실행을 해보면 다음과 같다.

$ pwd
/srv/workspace/barerepo

$ python ./dir.py
__file__                                                       = ./dir.py
os.path.dirname(__file__)                              = .
os.path.realpath(__file__)                              = /srv/workspace/barerepo/dir.py
os.path.realpath( os.path.dirname(__file__) )   = /srv/workspace/barerepo

os.getcwd()                                                 = /srv/workspace/barerepo

os.path.basename( os.path.realpath(__file__) ) = dir.py


dirname 은 상대경로를 알려주고 realpath 는 절대경로를 알려준다.
 
[ __file__ ] 예약어를 통해서 현재 경로를 확인하는 것에 대해서 살펴보고 있지만,
사실 지금 현재 경로를 알고 싶을 때에는 [ os.getcwd() ] 명령이 훨씬 더 많이 사용된다.

경로에서 파일이름만 뽑아내고 싶을 때에는 [ os.path.basename() ] 명령을 사용하면 된다.

반응형

+ Recent posts