Skip to content

Instantly share code, notes, and snippets.

@integrii
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save integrii/9856eb7fe1db0e0bb417 to your computer and use it in GitHub Desktop.
Save integrii/9856eb7fe1db0e0bb417 to your computer and use it in GitHub Desktop.
Get output of non-blocking bash commands with python
#!/usr/bin/python
# Be sure to run this as root!
import subprocess
def runcmd(command, timeout):
command = command + " & pid=$!;sleep " + str(timeout) + "; kill -9 $pid"
#print(command)
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
return process.stdout.read()
result = runcmd('hcidump', 5)
print(result)
@integrii
Copy link
Author

integrii commented Feb 6, 2015

It wasn't easy trying to get python to run a bash command for a limited time AND give me the output of it. I found a lot of custom modules and solutions for this, but prefer this hack I came up with that time-boxes the execution at the shell instead of within Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment