Popen(cmd, stdout=PIPE, stderr=PIPE)
이 부모 프로세스를 "잠금"하지 않습니다 [편집 스레딩에 대한 제거 가짜 조언과 덜 과장으로 제 주장을했다].
cmd
은 전체 파이프 버퍼로 인해 충분한 출력을 생성 할 경우 자체적으로 작동을 멈출 수 있습니다. 당신이 하위 프로세스 '출력을 폐기 할 경우 DEVNULL
대신 PIPE
의 사용
import os
from subprocess import Popen, STDOUT
DEVNULL = open(os.devnull, 'wb') #NOTE: it is already defined in Python 3.3+
p = Popen(cmd, stdout=DEVNULL, stderr=STDOUT)
# ...
당신이 다음 몇 가지 방법 사용할 수있는 메인 스레드를 차단하지 않고 출력을 처리 할 경우 : IOCP와 fcntl
, select
, 명명 된 파이프를, threads. 후자는 더 휴대용 방법 :
p = Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=-1)
bind(p.stdout, stdout_callback)
bind(p.stderr, stderr_callback)
# ...
곳 bind()
기능 :
import shutil
from threading import Thread
Thread(target=shutil.copy, args=['source-file', 'destination']).start()
:
from contextlib import closing
from functools import partial
from threading import Thread
def bind(pipe, callback, chunksize=8192):
def consume():
with closing(pipe):
for chunk in iter(partial(pipe.read, chunksize), b''):
callback(chunk)
t = Thread(target=consume)
t.daemon = True
t.start()
return t
당신은 메인 스레드를 차단하지 않고 파이썬에서 파일을 복사하는 외부 프로세스가 필요하지 않습니다
파이썬은 I/O 중에 GIL을 릴리즈 할 수 있으므로 복사는 메인 스레드와 동시에 그리고 병렬로 발생합니다.
여러 프로세스를 사용하는 스크립트를 비교할 수 :
import shutil
from multiprocessing import Process
Process(target=shutil.copy, args=['source-file', 'destination']).start()
을 당신이 당신의 프로그램이 다음 사망 True
에 thread_or_process.daemon
속성을 설정할 때 복사를 취소하십시오.
프로세스를 "잠금"한다는 것은 무엇을 의미합니까? 이것은 하위 프로세스가 종료 될 때까지 계속 대기합니다. (편집 : 질문이 편집되었습니다;이 의견은 "의사 소통"통화가 포함되어있을 때 더 의미가 있습니다) –
뭐가 문제입니까? ... 서브 프로세스는'comunnicate' 또는 다른 메소드를 호출 할 때까지 차단해서는 안됩니다 ... –
@JeremyRoman 왜 서브 프로세스가 끝날 때까지 기다릴까요? (Im은 거의 긍정적이며 산란 후 즉시 실행되지 않습니다.) –