当 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()