Featured image of post Creating an executable TOML

Creating an executable TOML

tutorial on creating an executable TOML

In this rather brief tutorial, I’m going to show you how to create an executable TOML, this works on Mac and Linux, it can also work on Windows using WSL . First you need to write a script, I’m going to use Python to write the script, it can be done in any programming language.

py_toml

#!/usr/bin/env python3
import sys
import tomllib


def open_shebang_toml() -> dict:
    try:
        # Shebang always add the filename of thepy
        # executing script as the last parameter
        with open(sys.argv[1], "rb") as f:
            return tomllib.load(f)
    except IndexError:
        print("Must have one argument", file=sys.stderr)
        exit(1)
    except (OSError, tomllib.TOMLDecodeError):
        print("Unable to read file", file=sys.stderr)
        exit(1)


def print_shebang():
    print(open_shebang_toml())
        

if __name__ == "__main__":
    print_shebang()

I called it py_toml yes that without the file extension, the file needs to be executable chmod 755 py_toml and need to searchable within PATH environment, I use direnv to update the PATH . Now to create the example TOML file.

example.toml

#!/usr/bin/env py_toml
# The trick is to use shebang
forename = "Chris"
surname = "Jackson"
location = "Jersey"

Again the file also needs to be executable, run the following command.

./example.toml

And you should get something like

{'forename': 'Chris', 'surname': 'Jackson', 'location': 'Jersey'}

Random Conclusion

It is quite useful, I used this approach to write my own rest api client for testing and I do use it for work, I could of used something like Postman or Insomnia, but I feel that those kind of client don’t follow the Unix philosophy quite well therefore I ended up writing my own client and yes it is written in Python rather than JavaScript, well because it the obvious choice for data analysis, analysing the output of the API is data analysis, it comes as standard on most Linux distributions as well, based on those two merit alone, I believe I have made the correct decision and performance is irrelevant for data analysis. 🙂

By performance I mean the speed of the programming language 🙂

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy