Programing

Python popen 명령.

lottogame 2020. 11. 21. 08:17
반응형

Python popen 명령. 명령이 완료 될 때까지 기다리십시오.


popen 셸 명령으로 시작하는 스크립트가 있습니다. 문제는 스크립트가 popen 명령이 완료 될 때까지 기다리지 않고 바로 이동이 계속된다는 것입니다.

om_points = os.popen(command, "w")
.....

쉘 명령이 완료 될 때까지 기다리도록 Python 스크립트에 어떻게 알릴 수 있습니까?


스크립트 작업 방식에 따라 두 가지 옵션이 있습니다. 명령을 차단하고 실행 중에는 아무 작업도하지 않으려면 subprocess.call.

#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

실행 중에 작업을 수행하거나에 항목을 공급 하려면 호출 후에 stdin사용할 수 있습니다 .communicatepopen

#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process

문서에 명시된 바와 같이 wait교착 상태가 될 수 있으므로 통신하는 것이 좋습니다.


subprocess이것을 달성하기 위해 사용할 수 있습니다 .

import subprocess

#This command could have multiple commands separated by a new line \n
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)

(output, err) = p.communicate()  

#This makes the wait possible
p_status = p.wait()

#This will give you the output of the command being executed
print "Command output: " + output

당신이 찾고있는 것은 wait방법입니다.


wait () 잘 작동합니다. 하위 프로세스 p1, p2 및 p3은 동시에 실행됩니다. 따라서 모든 프로세스는 3 초 후에 완료됩니다.

import subprocess

processes = []

p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)

processes.append(p1)
processes.append(p2)
processes.append(p3)

for p in processes:
    if p.wait() != 0:
        print("There was an error")

print("all processed finished")

전달하려는 명령을

os.system('x')

그런 다음 진술로 은밀하게

t = os.system('x')

이제 파이썬은 변수에 할당 될 수 있도록 명령 줄에서 출력을 기다릴 것 t입니다.

참고 URL : https://stackoverflow.com/questions/2837214/python-popen-command-wait-until-the-command-is-finished

반응형