Skip to content

Instantly share code, notes, and snippets.

@Qman11010101
Created February 27, 2020 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Qman11010101/d1d091cc82985a8434457e9a0f8a452d to your computer and use it in GitHub Desktop.
Save Qman11010101/d1d091cc82985a8434457e9a0f8a452d to your computer and use it in GitHub Desktop.
cfg2env(Python版)
# cfg2env Python Edition
# Require Python 3.7 or above
import os
import re
import sys
def main():
arg = sys.argv + [""]
if arg[1] == "":
configFile = input("Input filename: ")
else:
configFile = arg[1]
if os.path.exists(configFile):
with open(configFile, "r", encoding="utf-8_sig") as f:
txt = f.read()
envList = txt.split("\n")
for val in envList:
if val == "" or val.startswith("[") or val.startswith("#") or val.startswith(";"):
continue
element = [e.strip() for e in re.split("(=|:)", val, 1)] # maxsplit=1
if len(element) != 3:
print(f"Error: There is an invalid format in '{configFile}'. Please check it.")
continue
os.environ[element[0]] = element[2]
else:
print(f"Error: File '{configFile}' doesn't exists")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment