Python methods for reading environment variables and custom class sharing

Source: Internet
Author: User
use Os.environ to read and modify environment variables:

Copy the Code code as follows:


Import OS

Print (os.environ["TEMP"])

Mydir = "C:\\MyDir"
os.environ["MYDIR"] = MYDIR
Print (os.environ["MYDIR"])

PATHV = os.environ["PATH"]
Print (PATHV)
os.environ["path"]= Mydir + ";" + os.environ["path"]
Print (os.environ["PATH"])

Custom Python environment variable class:

Copy the Code code as follows:


Import OS

Class Myenv:

def __init__ (self):
Self.envfile = "C:\\myenv.txt"
Self.envs = {}

def setenvfile (self, filename):
Self.envfile = filename

def Save (self):
Outf = open (Self.envfile, "w")
If not OUTF:
Print ("Env file cannot is opened for write!")
For K, V in Self.envs.items ():
Outf.write (k + "=" + V + "\ n")
Outf.close ()

def Load (self):
inf = open (Self.envfile, "R")
If not INF:
Print ("Env file cannot is opened for open!")
For line in Inf.readlines ():
K, V = line.split ("=")
Self.envs[k] = V
Inf.close ()

def ClearAll (self):
Self.envs.clear ()

def addenv (self, k, V):
Self.envs[k] = V

def removeenv (self, k):
Del Self.envs[k]

def printall (self):
For K, V in Self.envs.items ():
Print (k + "=" + V)

if __name__ = = "__main__":
Myenv = Myenv ()
Myenv.setenvfile ("C:\\myenv.txt")
Myenv.load ()
Myenv.addenv ("MYDIR", "C:\\MyDir")
Myenv.addenv ("MYDIR2", "C:\\mydir2")
Myenv.addenv ("MYDIR3", "C:\\mydir3")
Myenv.save ()
Myenv.printall ()

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.