Last active
October 13, 2022 19:19
-
-
Save cgobat/238525c92162caa1947a4d03b8f879c5 to your computer and use it in GitHub Desktop.
NAIF CSPICE executable utilities made available within Python
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 os, sys, platform | |
import subprocess | |
CSPICE_dir = "/absolute/path/to/cspice/" | |
__doc__ = """ | |
SPICE executables, made available from within Python. | |
Available executables: | |
""" + "\n".join([os.path.splitext(exe)[0] for exe in os.listdir(os.path.join(CSPICE_dir,"exe"))]) + """ | |
""" | |
def _exe(util: str, args: list[str]): # general-purpose function to run any of the executables | |
OS_name = platform.system() | |
if OS_name == "Windows" or "CYGWIN" in OS_name: | |
extension = ".exe" | |
elif OS_name in ("Linux","Darwin"): | |
extension = "" | |
else: | |
extension = "" | |
print("Warning! Operating system not recognized. Extension may be incorrect.") | |
executable = os.path.join(CSPICE_dir, "exe", util+extension) | |
if isinstance(args, str): | |
arguments = [args] | |
elif isinstance(args, list): | |
arguments = args | |
else: | |
raise TypeError("Single argument should be a str, multiple should be a list of str.") | |
cmd = [executable]+[arguments] | |
cmd_out = subprocess.check_output(cmd, text=True) | |
return cmd_out | |
def _docs(util): # retrieve documentation contents from file | |
with open(CSPICE_dir+f"/doc/{util}.ug","r") as ug: | |
doc_contents = ug.read() | |
return doc_contents | |
def _construct(util): # create a Python function for an executable and add it to the namespace | |
func = lambda args : _exe(util,args) | |
func.__doc__ = _docs(util) | |
globals()[util] = func | |
for executable in os.listdir(CSPICE_dir+"/exe/"): # construct a function for all of the available exes | |
_construct(os.path.splitext(executable)[0]) | |
if __name__ == "__main__": | |
util_to_run = sys.argv[1] # executable name | |
arguments = sys.argv[2:] # arguments to pass | |
func = globals()[util_to_run] | |
print("Running",func,arguments) | |
print(func(arguments)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment