티스토리 뷰
python을 이용하여 command 명령과 os 명령을 이용하여 폴더를 생성하고, 리스팅을 할 수 있는 코드가 있습니다. glob라는 함수가 있지만 이상하게 처리가 안됩니다. 그 외에 더 많은 조합들이 있고, 대부분의 명령어를 스크립트로 제공하고 있고, os에는 Link 도 생성 할 수 있습니다.
Python os 명령 문서
http://docs.python.org/library/os.html
Python commands 문서
http://docs.python.org/library/commands.html?highlight=commands#commands
간단하게 command 명령, os 명령, permission 명령을 사용한 예제코드입니다.
command 및 os 명령
commands.getstatusoutput() 명령을 이용하여 직접 쉘 명령을 사용 할 수 있습니다. 아래 결과 화면은 폴더를 생성하고, ls 명령어를 사용하여 결과를 확인한 코드입니다. 그 외 subprocess의 Popen 을 이용한 예제코드도 함께 있습니다.
소스코드
'''import commands
failure, output = commands.getstatusoutput("ls")
if failure:
print 'Failed\n'
sys.exit(1)
print output'''
'''from subprocess import Popen, PIPE
popen = Popen("ls", shell=True, stdout=PIPE)
output, error = popen.communicate()
print output'''
'''import commands
import sys
def faile_check(fail):
if fail:
print 'Failed\n'
sys.exit(1)
fail, output = commands.getstatusoutput("ls")
faile_check(fail)
print output
fail, out = commands.getstatusoutput("touch a.txt")
faile_check(fail)
fail, output = commands.getstatusoutput("ls")
print output'''
'''from subprocess import Popen, PIPE
popen = Popen("ls", shell=True, stdout=PIPE)
out, error = popen.communicate()
print out
popen2 = Popen("touch b.txt", shell=True, stdout=PIPE)
popen2.communicate()
popen = Popen("ls", shell=True, stdout=PIPE)
out, error = popen.communicate()
print out'''
import os
import commands
myfile = 'thdev'
os.mkdir(myfile)
fail, output = commands.getstatusoutput("ls")
print output
os.rmdir(myfile)
print '\n'
fail, output = commands.getstatusoutput("ls")
print output
예제 코드 출력
OS 예제 코드
os.listdir() 을 사용하여 특정 경로를 리스팅 하는 코드와 현재 디록토리 python을 실행 하는 현재 디렉토리를 리스팅하는 코드입니다. 그리고 os.path.isfile(), os.path.isdir(), os.path.islink()를 확인하는 함수 및 파일의 수정시간, 생성시간, 용량 정보를 가져오는 예제코드입니다.
소스코드
import os
files = os.listdir("/home/taehwan/")
curfiles = os.listdir(os.curdir)
print files
print '\n'
print curfiles
print '\n'
myown = 'test'
if os.path.isfile(myown):
print 'plain file'
elif os.path.isdir(myown):
print 'directory'
elif os.path.islink(myown):
print 'link'
else:
print 'nothing'
last_acc = os.path.getatime('a.txt')
last_modification = os.path.getmtime('a.txt')
size = os.path.getsize('a.txt')
print last_acc, last_modification, size
결과 화면
Permission
os.access를 이용하여 a.txt 파일이 읽기 권환이 있는지 확인하는 코드입니다. os.access(파일, 권환)값을 넘겨주면 true, false를 return합니다.
소스코드
import time, os myfile = 'a.txt' if os.access(myfile, os.R_OK): print myfile, ' read permission'
결과화면
'Programming language' 카테고리의 다른 글
| MemSQL 간단하게 살펴보기.. (0) | 2012.06.26 |
|---|---|
| 구조체를 파일로 저장, 불러오기 (0) | 2012.06.16 |
| Python 파일 입출력 예제코드 (1) | 2012.06.14 |
| MFC에서 Chart를 쉽게 그리는 라이브러리 ChartDirector (25) | 2012.06.12 |
| Google-Blockly으로 미로 찾기 짜보기 (2) | 2012.06.04 |
댓글