进入交互模式是我们预期之外的,记录一下。
进入交互之后linux一直等待你的输入,所有subprocess.getoutput()
就一直卡着呢~,我们加入timeout
通过学习subprocess
中支持timeout
有:
getoutput
并不支持timeout参数
尝试了call check_all check_output
这几个方法之后并不能解决Linux 交互超时问题。
chatgpt的答案:
import subprocess
try:
cmd = 'sleep 11'
process = subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate(timeout=10)
# 执行成功
print(output)
except subprocess.TimeoutExpired:
# 超时事例
process.kill() # 终止子进程
直接获取到子进程,超时后直接kill掉
升级版:
def exe_cmd(cmd,timeout=15):
code = 0
res = None
try:
process = subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate(timeout=timeout)
output = output.decode()
error = error.decode()
if output:
print('命令 %s执行成功' % cmd)
print(output)
code = 0
res = output
if error:
print('命令 %s执行失败' % cmd)
print(error)
code = 0
res = output
if not output and not error:
print('命令执行没有结果')
res = None
except BaseException as e:
# 超时事例
print(e)
print('执行命令超时')
res = e
code = '1'
process.kill() # 终止子进程
finally:
return code, res
标签:cmd,subprocess,getoutput,timeout,error,print,output
From: https://www.cnblogs.com/tarzen213/p/17491964.html