Last active
June 1, 2016 02:53
-
-
Save jenglamlow/80ff4b1581d0724dbbadee7bc99622dc to your computer and use it in GitHub Desktop.
Create config.yaml when not exist
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
| import sys | |
| import yaml | |
| import os | |
| import getpass | |
| def touch(fname, times=None): | |
| with open(fname, 'a'): | |
| os.utime(fname, times) | |
| def config_init(): | |
| base_dir = os.path.dirname(os.path.realpath(sys.argv[0])) | |
| config_file = base_dir + os.path.sep + "config.yaml" | |
| tag_list = ["username", "password", "ip", "domain", "project"] | |
| # Similar to unix touch | |
| touch(config_file) | |
| # Load config YAML file | |
| stream = open(config_file, 'r') | |
| config = yaml.load(stream) | |
| # Initialize config dictionary if config file is empty | |
| if config is None: | |
| config = {} | |
| # Check for mandantory tag | |
| for tag in tag_list: | |
| # Ask for user input if tag not exist or tag is empty | |
| if tag not in config or not config[tag]: | |
| if tag != "password": | |
| prompt = tag + ": " | |
| config[tag] = input(prompt) | |
| # Clear password when user input username | |
| if tag == "username": | |
| config["password"] = "" | |
| else: | |
| prompt = "password for " + config["username"] + ": " | |
| config[tag] = getpass.getpass(prompt) | |
| # Update the config file | |
| with open(config_file, 'w') as f: | |
| f.write(yaml.dump(config, default_flow_style=False)) | |
| def main(): | |
| config = config_init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment