Created
January 30, 2020 10:16
-
-
Save letam/ee09eaac400fd833e229c9e7e31f9464 to your computer and use it in GitHub Desktop.
Utility to execute simple command-line programs through python, for use in python shell scripts.
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 | |
""" | |
Utility to execute "simple" (non-daemon) command-line programs through python, | |
for use in python shell scripts. | |
WARNING: As this script can trigger any command-line process, | |
please be careful not to ruin your system. | |
""" | |
from typing import List, Union | |
import os, shlex, sys | |
from subprocess import PIPE, Popen | |
env = os.environ.copy() | |
class Process: | |
"""Encapsulate useful values returned by subprocess execution, for use in command-line scripts.""" | |
cmd: str | |
out: str = "" | |
err: str = "" | |
returncode: int | |
def __init__(self, args: Union[str, List[str]], print=True): | |
if type(args) == str: | |
self.cmd = interpret_cmd_from_string(args) | |
else: | |
self.cmd = args | |
pipes = Popen(self.cmd, stdout=PIPE, stderr=PIPE, env=env) | |
stdout, stderr = pipes.communicate() | |
if stderr: | |
self.err = stderr.decode() | |
if print: | |
sys.stderr.write(self.err) | |
if stdout: | |
self.out = stdout.decode() | |
if print: | |
sys.stdout.write(self.out) | |
if print: | |
sys.stdout.flush() | |
self.returncode = pipes.returncode | |
@property | |
def ok(self) -> bool: | |
return self.returncode == 0 | |
@property | |
def lines(self) -> List[str]: | |
s = self.err | |
if self.out: | |
s = self.out | |
return [line for line in s.split("\n") if line != ""] | |
def interpret_cmd_from_string(args: str) -> List[str]: | |
"""Given a command string, return a subprocess-compatible argument list..""" | |
if not args: | |
raise Exception("No command args provided.") | |
if "~" in args: | |
args = args.replace("~", os.path.expanduser("~")) | |
args = shlex.split(args) | |
return args | |
# To run on the command line: | |
if __name__ == "__main__": | |
args = " ".join(sys.argv[1:]) | |
Process(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment