-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimal_example.py
More file actions
51 lines (43 loc) · 1.73 KB
/
Copy pathminimal_example.py
File metadata and controls
51 lines (43 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3
import asyncio
async def run_command(cmd, timeout=5.0):
"""Run a shell command asynchronously with a timeout."""
print(f"Running command: {cmd}")
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
stdout_str = stdout.decode() if stdout else ""
stderr_str = stderr.decode() if stderr else ""
print(f"Command completed with return code: {process.returncode}")
print(f"STDOUT: {stdout_str[:100]}{'...' if len(stdout_str) > 100 else ''}")
if stderr_str:
print(f"STDERR: {stderr_str[:100]}{'...' if len(stderr_str) > 100 else ''}")
return process.returncode, stdout_str, stderr_str
except asyncio.TimeoutError:
print(f"Command timed out after {timeout} seconds!")
try:
process.kill()
print("Process was killed")
except ProcessLookupError:
print("Process already terminated")
raise TimeoutError(f"Command '{cmd}' timed out")
async def main():
print("=== Testing Successful Command ===")
try:
await run_command("echo 'Hello, world!'")
print("Command executed successfully\n")
except Exception as e:
print(f"Error: {e}\n")
print("=== Testing Command That Will Timeout ===")
try:
await run_command("sleep 10 && echo 'This should not print'", timeout=2.0)
print("Command executed successfully\n")
except Exception as e:
print(f"Error: {e}\n")
if __name__ == "__main__":
asyncio.run(main())
print("Done!")