Created
October 10, 2017 22:54
-
-
Save wecsam/d40b510f09deed56bd997460358ad756 to your computer and use it in GitHub Desktop.
Substitutes environment variables into the given path
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
#!/usr/bin/python3 | |
import os, sys | |
# This script takes a string as an argument and outputs the same path with as many | |
# environment variables substituted in as possible. | |
def variable_syntax(variable_name): | |
try: | |
return { | |
"nt": lambda variable_name: "%" + variable_name + "%", | |
"posix": lambda variable_name: "$" + variable_name | |
}[os.name](variable_name) | |
except KeyError: | |
quit("This operating system is not supported.") | |
def envify(path): | |
# Start with the environment variable with the longest value. | |
for variable_name, value in envify.environ: | |
# Replace instances of the value of the environment variable with | |
# the name of the environment variable. | |
path = path.replace(value, variable_syntax(variable_name)) | |
return path | |
def envify_refresh(): | |
# Get a list of environment variables sorted by value length in descending order. | |
# Each element is a tuple like (variable name, value). | |
envify.environ = sorted(os.environ.items(), key=lambda variable: len(variable[1]), reverse=True) | |
envify_refresh() | |
def main(argc, argv): | |
if argc < 2: | |
print("Pass a path in as an argument.") | |
else: | |
# Iterate through all arguments, skipping the first. | |
arguments = iter(argv) | |
next(arguments) | |
for path in arguments: | |
print(envify(path)) | |
if __name__ == "__main__": | |
main(len(sys.argv), sys.argv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment