當 subprocess.Popen
方法運行程序卡住時,有幾種可能的原因和解決方法:
communicate()
方法等待子進程完成。例如:process = subprocess.Popen(['command'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
communicate()
方法讀取子進程的輸出并清空緩沖區。例如:process = subprocess.Popen(['command'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
或者使用 stdout.read()
方法讀取子進程的輸出。例如:
process = subprocess.Popen(['command'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.read()
communicate()
方法向子進程提供輸入。例如:process = subprocess.Popen(['command'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate(input='input_data')
timeout
參數設置超時時間,并使用 process.wait(timeout)
方法等待子進程完成。例如:process = subprocess.Popen(['command'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
output, error = process.communicate()