파이썬 외부 프로그램 종료 - paisseon oebu peulogeulaem jonglyo

파이썬 3.5 이후 버전에서 다른 프로그램을 실행하기 위해서는 subprocess 모듈의 run() 함수를 사용하면 됩니다. subprocess.run()은 실행후 외부 프로그램이 실행 왼료되면 CompletedProcess를 반환하며 returncode등의 결과를 가지고 있습니다.

>>> import subprocess
>>> a = subprocess.run(['ls', '-al'])
total 0
drwxr-xr-x  2 jlim  staff   64 11 Sep 23:45 .
drwxr-xr-x  9 jlim  staff  288 11 Sep 23:45 ..
>>> print(a)
CompletedProcess(args=['ls', '-al'], returncode=0)

 

파이썬 3.5 이전 버전을 사용하고 있다면 subprocess.call() 함수를 사용할 수 있습니다. 

import subprocess
subprocess.call(['ls', '-al']

 

아래와 같이 os.system()함수를 사용할 수 도 있습니다. 하지만 subprocess 모듈이 외부 프로그램의 실행 결과를 얻어오는데 os.system() 보다 더 강력하기 때문에 파이썬 공식 문서에서는 subprocess 모듈을 사용하는것을 추천하고 있습니다. 

import os
os.system('ls -al')

 

 

 

공유하기

게시글 관리

구독하기J's 어썸랩

저작자표시 비영리 변경금지

  • 카카오스토리
  • 트위터
  • 페이스북

'파이썬 > 자주하는 질문' 카테고리의 다른 글

파이썬(Python) 딕셔너리 값(value)로 정렬하기  (0)2020.09.13파이썬(Python) *args **kwargs 는 무엇일까?  (0)2020.09.12파이썬(Python) yield 키워드 이해하기  (0)2020.09.11파이썬(Python) if __name__ == '__main__': 은 무엇일까?  (0)2020.09.11파이썬(Python) 문자열을 in-place로 수정하는 방법  (0)2020.09.10

atexit 모듈은 정리 함수를 등록하고 해제하는 함수를 정의합니다. 이렇게 등록된 함수는 정상적인 인터프리터 종료 시 자동으로 실행됩니다. atexit는 이 함수들을 등록된 역순 으로 실행합니다; A, B, C 를 등록하면, 인터프리터 종료 시각에 C, B, A 순서로 실행됩니다.

참고: 이 모듈을 통해 등록된 함수는 다음과 같은 경우 호출되지 않습니다. 프로그램이 파이썬이 처리하지 않는 시그널에 의해 종료될 때. 파이썬의 치명적인 내부 에러가 감지되었을 때.

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
2 가 호출될 때.

버전 3.7에서 변경: C-API 서브 인터프리터와 함께 사용될 때, 등록된 함수는 등록된 인터프리터에 국지적입니다.

atexit.register(func, *args, **kwargs)

func 를 종료 시에 실행할 함수로 등록합니다. func 에 전달되어야 하는 선택적 인자는

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
3 에 인자로 전달되어야 합니다. 같은 함수와 인자를 두 번 이상 등록 할 수 있습니다.

정상적인 프로그램 종료 시에 (예를 들어,

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
4 가 호출되거나 주 모듈의 실행이 완료된 경우에), 등록된 모든 함수는 후입선출 순서로 호출됩니다. 낮은 수준의 모듈은 일반적으로 상위 수준 모듈보다 먼저 임포트 되기 때문에 나중에 정리해야 한다는 가정입니다.

If an exception is raised during execution of the exit handlers, a traceback is printed (unless

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
5 is raised) and the exception information is saved. After all exit handlers have had a chance to run, the last exception to be raised is re-raised.

이 함수는 func 을 반환하므로 데코레이터로 사용할 수 있습니다.

atexit.unregister(func)

Remove func from the list of functions to be run at interpreter shutdown.

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
6 silently does nothing if func was not previously registered. If func has been registered more than once, every occurrence of that function in the atexit call stack will be removed. Equality comparisons (
def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
8) are used internally during unregistration, so function references do not need to have matching identities.

더 보기

모듈
def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
9

def goodbye(name, adjective):
    print('Goodbye %s, it was %s to meet you.' % (name, adjective))

import atexit

atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective='nice', name='Donny')
9 히스토리 파일을 읽고 쓰는 atexit 의 유용한 예.

atexit 예제¶

다음의 간단한 예제는, 모듈이 임포트 될 때 파일에서 카운터를 읽고 프로그램이 종료할 때 프로그램의 명시적인 호출에 의존하지 않고 카운터의 변경된 값을 자동으로 저장하는 방법을 보여줍니다.: