Last active
August 29, 2015 14:05
-
-
Save genba/8d6dd68646e6d89a0ba1 to your computer and use it in GitHub Desktop.
run_cmd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shlex | |
import subprocess | |
def run_cmd(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, block=True, *args, **kwargs): | |
""" | |
Run a command using the subprocess module. | |
:param cmd: command to be executed | |
:type cmd: str or list | |
:return: process object | |
:rtype: subprocess.Process | |
""" | |
if isinstance(cmd, str): | |
cmdargs = shlex.split(cmd) | |
elif isinstance(cmd, list): | |
cmdargs = cmd | |
else: | |
raise ValueError('command must be either a string or a list') | |
proc = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, *args, **kwargs) | |
if block: | |
proc.wait() | |
# FIXME: this will block if you use pipes and the process produces too much output! | |
# TODO: for that case, we should use proc.communicate()! | |
# The question now is: if we don't use pipes, is it still safe to use proc.communicate() with the assurance that | |
# it will not read the stdout/stderr? | |
else: | |
# If neither wait nor poll are executed, returncode is not set | |
# (i.e. it will be None until wait/poll is executed) | |
proc.poll() | |
return proc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment