Last active
January 30, 2020 05:28
-
-
Save letam/7f3dcad8239ee1340f3eab8d66f7702e to your computer and use it in GitHub Desktop.
All-in-one function to execute command-line programs through python
This file contains hidden or 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
#!/usr/bin/env python3 | |
''' | |
Execute "simple" (non-daemon) command-line programs through python, for use in python shell scripts. | |
Rationale: Python scripting seems more fun than bash scripting. | |
WARNING: Use at your own risk. I am not liable for the destruction of your system. | |
''' | |
from typing import Tuple | |
import os, shlex | |
from subprocess import PIPE, Popen, CalledProcessError | |
env = os.environ.copy() | |
def sh_execute(command: str) -> Tuple[str, str]: | |
if not command: | |
raise Exception('No command provided.') | |
if '~' in command: | |
command = command.replace('~', os.path.expanduser('~')) | |
args = shlex.split(command) | |
pipes = Popen(args, stdout=PIPE, stderr=PIPE, env=env) | |
stdout, stderr = pipes.communicate() | |
out, err = stdout.decode(), stderr.decode() | |
if pipes.returncode != 0: | |
raise ShError(pipes.returncode, args, output=out, stderr=err) | |
return out, err | |
shex = sh_execute | |
class ShError(CalledProcessError): | |
"""Raised when sh_execute() is called and the process | |
returns a non-zero exit status. | |
Attributes: | |
cmd, returncode, stdout, stderr, output | |
""" | |
pass | |
def pshex(command: str) -> None: | |
''' Execute and then print the output of sh_execute. ''' | |
try: | |
out, err = sh_execute(command) | |
except ShError as err: | |
print(err.stderr, end='', flush=True) | |
else: | |
if err: | |
print(err, end='', flush=True) | |
if out: | |
print(out, end='', flush=True) | |
# For testing on the command line: | |
if __name__ == '__main__': | |
import sys | |
command = ' '.join(sys.argv[1:]) | |
pshex(command) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment