파이썬의 서브 프로세스에 문제가 있습니다. 팝업 방법.자식 프로세스가 종료 될 때까지 subprocess.Popen이 대기하지 않는 이유는 무엇입니까?
다음은 문제를 보여주는 테스트 스크립트입니다. 그것은 리눅스 박스에서 실행되고 있습니다.
success: 100000
하지만 때로는 실패의 경우, 즉시 삽입 후 선택 0 행하지만 이후에 표시되는지
failure: 0
after sleeping the count is 100000
주의 :
#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some rows from a source table to a destination table
# note that the destination table is empty when this script is run
cmd = 'mysql -u ve --skip-column-names --batch --execute="insert into destination (select * from source limit 100000)" test'
run(cmd)
# check to see how many rows exist in the destination table
cmd = 'mysql -u ve --skip-column-names --batch --execute="select count(*) from destination" test'
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
# if subprocess.Popen() waited for the child to terminate than count should be
# greater than 0
if count > 0:
print "success: " + str(count)
else:
print "failure: " + str(count)
time.sleep(5)
# find out how many rows exists in the destination table after sleeping
process = run(cmd)
count = (int(process.communicate()[0][:-1]))
print "after sleeping the count is " + str(count)
보통이 스크립트의 출력은 5 초 동안 잠을 자면 두 번째 선택에서 100000의 행 수가 올바르게 표시됩니다. 내 결론은 다음 중 하나가 참이라는 것입니다.
,- subprocess.Popen가 종료 자식 스레드를 대기하지 않습니다 -이 문서를 모순되는 것처럼 보인다
- MySQL의 삽입은 원자 아니다 - MySQL의 나의 이해는
- 선택이 아닌 삽입 원자임을 표시하는 것 지금 당장 올바른 행 수를 보는 것 - 내가하는 것보다 MySQL을 잘 아는 친구에 따르면
무엇이 누락 되었습니까?
참고로, 저는 이것이 파이썬과 MySQLdb에서 mysql과 상호 작용하는 해킹 방법이라는 것을 알고 있습니다. MySQLdb에는이 문제가 없을 가능성이 있지만이 방법이 작동하지 않는 이유에 대해 궁금합니다.
감사합니다 여러분. 하위 프로세스 문서를 다시 보면 Popen 메서드 섹션이 아닌 편의 메서드 섹션에 나타나는 "명령을 기다리는 중입니다"라는 주석이 표시됩니다. 나는 Jed의 답변에 고개를 끄덕였다. 왜냐하면 내 미래의 스크립팅 요구에 Paul의 솔루션을 사용할 것이라고 생각하기는하지만 원래의 질문에 가장 잘 답변했기 때문이다. –
os.system은 (다른 것을 사용하지 않는 한) 프로세스의 반환 값 (보통 0 또는 1)을 반환합니다. 그것도 당신을 물게하지 마라. –