Skip to content

Commit 8979812

Browse files
authored
Update linux_command_demo.py
1 parent 2d09e7a commit 8979812

1 file changed

Lines changed: 29 additions & 2 deletions

File tree

demo/linux_command_demo.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,31 @@
1-
import subprocess
1+
from subprocess import Popen, PIPE
2+
import threading
3+
import os
4+
import signal
25

36

4-
def exec_cmd(cmd, interact=False):...
7+
# def exec_cmd(cmd, interact=False):...
8+
9+
class Command():
10+
"""Python 2.7.5 带有超时功能的 subprocess"""
11+
status = -1
12+
output = error = ""
13+
14+
def __init__(self):
15+
self.process = None
16+
17+
def run(self, cmd, timeout=60):
18+
def target():
19+
self.process = Popen(cmd, shell=True, stdin=PIPE,
20+
stderr=PIPE, stdout=PIPE, preexec_fn=os.setsid)
21+
self.output, self.error = self.process.communicate()
22+
self.output = self.output.strip()
23+
self.status = self.process.returncode
24+
25+
thread = threading.Thread(target=target)
26+
thread.start()
27+
thread.join(timeout)
28+
if thread.is_alive():
29+
os.killpg(self.process.pid, signal.SIGTERM)
30+
thread.join()
31+
return self.status, self.output, self.error

0 commit comments

Comments
 (0)