Skip to content

Instantly share code, notes, and snippets.

@ric03uec
Last active August 29, 2015 14:02
Show Gist options
  • Save ric03uec/f6344853133b458b4d88 to your computer and use it in GitHub Desktop.
Save ric03uec/f6344853133b458b4d88 to your computer and use it in GitHub Desktop.
python subprocess i/o redirection
$ ./runner.py
__NO_REDIRECTION_ON_PARENT__
------ executing main thread ----------
----- parent stdout --------
executing script 1
executing script 2
----- parent stderr --------
script2.sh: line 4: la: command not found
retcode: 127
thread done
__PARENT_STDERR_REDIRECTED_TO_STDOUT__
------ executing main thread ----------
----- parent stdout --------
executing script 1
executing script 2
script2.sh: line 4: la: command not found
----- parent stderr --------
retcode: 127
thread done
#!/usr/bin/python
import os, sys, subprocess
import threading
def exec_cmd(cmd):
cmd_proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
timeout = 600
thread_res = {}
def exec_cmd_thread(result):
print '------ executing main thread ----------'
out = ""
err = ""
print '\n----- parent stdout --------'
for line in iter(cmd_proc.stdout.readline, ''):
sys.stdout.write(line)
out += line
print '\n----- parent stderr --------'
for line in iter(cmd_proc.stderr.readline, ''):
sys.stdout.write(line)
err += line
cmd_proc.communicate()
print "\nretcode: {0}\n".format(cmd_proc.returncode)
thread = threading.Thread(target=exec_cmd_thread, args=(thread_res,))
thread.start()
thread.join(7)
if thread.is_alive():
print 'thread alive... killing'
cmd_proc.terminate()
else:
print 'thread done'
def exec_cmd_no_redirect():
print "\n__NO_REDIRECTION_ON_PARENT__"
cmd = "/bin/bash <path_to_script_1.sh>"
exec_cmd(cmd)
def exec_cmd_redirect():
print "\n__PARENT_STDERR_REDIRECTED_TO_STDOUT__"
cmd = "/bin/bash <path_to_script_1.sh> 2>&1"
exec_cmd(cmd)
exec_cmd_no_redirect()
exec_cmd_redirect()
#!/bin/bash -x
echo 'executing script 1'
/bin/bash script2.sh
#!/bin/bash -x
echo 'executing script 2'
la
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment