1 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超4個(gè)贊
有多種方法可以做到這一點(diǎn),但可能最簡單的方法是調(diào)用subprocess.check_output()方法,該方法允許您以秒為單位指定超時(shí)值,并且還返回子進(jìn)程生成的文本,即:
[...]
while True:
command = connection.recv(BUFFER_SIZE) # receive message from client
if not command:
break
command = command.decode("utf-8").strip()
if len(command) > 0:
try:
output_as_string = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True, timeout=5.0).decode("utf-8")
except subprocess.TimeoutExpired:
output_as_string = "Sub-process timed out!\r\n"
connection.send(str.encode("0:") + str.encode(output_as_string))
[...]
添加回答
舉報(bào)